-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
docs: prefer useState in createContext example #2995
base: main
Are you sure you want to change the base?
Conversation
Both useState and useRef are correct in practice: useState will only render once since we never set the state after initializion, and useRef is safe to use since the component never needs to rerender when the ref value changes. However, lint rules will flag useRef as a mistake, because we are passing a ref value to a child component, which in general can cause stale components since changing refs doesn't trigger re-renders.
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
This pull request is automatically built and testable in CodeSandbox. To see build info of the built libraries, click here or the icon next to each commit SHA. |
Is it eslint-plugin-react-hooks or eslint-plugin-react-compiler? |
It's react-compiler
|
Can you look for official info from the compiler team that recommends useState over useRef for lazy initialization? |
I'd say it falls under https://react.dev/learn/referencing-values-with-refs#differences-between-refs-and-state
I think they didn't want to special case 'useRef but you never update .current', and they would rather recommend 'useState without ever callling the setter' for immutable data which is used during render. |
I would like to see if it's officially unsupported with the compiler. Maybe we should wait for the compiler to be out of the experimental phase. |
Looks like it's being discussed, I asked a question here: facebook/react#30843 (comment) |
The compiler does support this pattern, but you have to specifically check that against null, ie |
Cool. Does it work with |
Related Bug Reports or Discussions
N/A
Summary
This PR edits the 'context usage' example from the docs to use state, rather than a ref, to hold the zustand store.
Both useState and useRef are correct in practice: useState will only render once since we never set the state after initialization, and useRef is safe to use since the component never needs to rerender when the ref value changes.
However, lint rules will flag useRef as a mistake, because we are passing a ref value to a child component, which in general can cause stale components since changing refs doesn't trigger re-renders.
Check List
pnpm run fix:format
for formatting code and docs