-
Notifications
You must be signed in to change notification settings - Fork 7.7k
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
[Mistake]: nextId++ is violating React's principle of purity #7497
Comments
I'll fix this. |
It’s not used for rendering so it’s not a problem. It’s not state in that sense. |
@gaearon Wouldn’t storing nextId in state be a more robust and scalable solution in larger apps? I'm referring to challenge #3's solution in https://react.dev/learn/updating-arrays-in-state |
I guess, but I think he wants to say that the variables only need to be states if they are going to cause a re-render. But in this case, nextId does not affect the dom in any way, so this would be unnecessary. |
There's no reason to store |
@gaearon exactly, understood! Thanks for the clarification! |
Ok, thanks! @gaearon |
Summary
nextId++ is mutating a (global) variable declared outside the component, violating React's principle of immutability.
Page
https://react.dev/learn/updating-arrays-in-state
Details
React expects state updates to be pure (immutable).
nextId is not stored in useState, therefore, nextId++ mutates a global variable outside of React’s state system.
The text was updated successfully, but these errors were encountered: