Skip to content

Creating a Selector #587

Closed Answered by dai-shi
untlsn asked this question in Q&A
Nov 4, 2022 · 2 comments · 1 reply
Discussion options

You must be logged in to vote

Yes, that approach works.
See also: https://github.com/pmndrs/valtio/wiki/How-to-avoid-rerenders-manually#subscribe-and-set-local-state-conditionally

const useSelector = (proxyObject, selector) => {
  const [slice, setSlice] = useState(() => selector(proxyObject))
  useEffect(() => subscribe(proxyObject, () => setSlice(selector(proxyObject))), [proxyObject])
  return slice
}

(☝️ It requires selector to be stable.)

If you use uSES, you need to use useCallback for stable subscribe function.

const useProxySelector = <Proxy extends object, T>(proxy: Proxy, selector: (state: Proxy) => T) => (
  useSyncExternalStore(
    useCallback((syncSub) => subscribe(proxy, syncSub), [proxy]),
    () => se…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Answer selected by untlsn
Comment options

You must be logged in to vote
1 reply
@dai-shi
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants