Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

why not using useSyncExternalStoreWithSelector ? #25

Open
scr2em opened this issue Nov 29, 2023 · 1 comment
Open

why not using useSyncExternalStoreWithSelector ? #25

scr2em opened this issue Nov 29, 2023 · 1 comment

Comments

@scr2em
Copy link

scr2em commented Nov 29, 2023

import { listenKeys } from 'nanostores'
import { useCallback, useSyncExternalStore } from 'react'

export function useStore(store, opts = {}) {
  let subscribe = useCallback(
    onChange =>
      opts.keys
        ? listenKeys(store, opts.keys, onChange)
        : store.listen(onChange),
    [opts.keys, store]
  )

  let get = store.get.bind(store)

  return useSyncExternalStore(subscribe, get, get)
}

isn't it better to use useSyncExternalStoreWithSelector to replace listening for keys ?
example

const atom = Atom({name: 'jo', age : 21})

const age = useStore(atom, (state)=> state.age) // and only re-renders when the age is changes 

@TrySound
Copy link

useSyncExternalStoreWithSelector is some kinda experimental api and not part of react. Using it would require to install additional package.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants