-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
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
Comments
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. |
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]);
}
|
no, you want to support changing the selector.
this doesn't work, if state is not changed, but only props.key changes. |
Ah gotcha! The resulting state will be stale until the underlying state itself changes. |
I've noticed for a few state libraries, including zustand, use
useRef
, diff the previous value and then forceRender(), instead of leaving this touseState
which does all this for free. Why is that?My guess it's something to do with isomorphic layouts?
The text was updated successfully, but these errors were encountered: