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

Question: Why do hooks useRef instead of useState #719

Closed
mfbx9da4 opened this issue Dec 21, 2021 · 4 comments
Closed

Question: Why do hooks useRef instead of useState #719

mfbx9da4 opened this issue Dec 21, 2021 · 4 comments

Comments

@mfbx9da4
Copy link

mfbx9da4 commented Dec 21, 2021

I've noticed for a few state libraries, including zustand, use useRef, diff the previous value and then forceRender(), instead of leaving this to useState which does all this for free. Why is that?

My guess it's something to do with isomorphic layouts?

@dai-shi
Copy link
Member

dai-shi commented Dec 21, 2021

basically, it's to support inline (non-memoized) selectors (and to avoid re-subscribing when selectors change).

with #550, we no longer have explicit useRef.

@mfbx9da4
Copy link
Author

mfbx9da4 commented Dec 21, 2021

Thanks for your prompt response.

But can't you support non-memoized selectors and avoid re-subscribing like so:

function useStore(selector) {
  const ref = useRef({ selector }).current;
  ref.selector = selector;
  const [state, setState] = useState(selector(value));
  useEffect(() => subscribe(x => setState(ref.selector(x))), []);
  return useMemo(() => [state, set], [state]);
}
  • Selector always stays up to date
  • Don't resubscribe every time the selector changes

@dai-shi
Copy link
Member

dai-shi commented Dec 21, 2021

no, you want to support changing the selector. useStore(state => state[props.key])

Selector always stays up to date

this doesn't work, if state is not changed, but only props.key changes.

@mfbx9da4
Copy link
Author

Ah gotcha! The resulting state will be stale until the underlying state itself changes.

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