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

[Mistake]: nextId++ is violating React's principle of purity #7497

Closed
behanprw opened this issue Feb 14, 2025 · 7 comments
Closed

[Mistake]: nextId++ is violating React's principle of purity #7497

behanprw opened this issue Feb 14, 2025 · 7 comments
Assignees

Comments

@behanprw
Copy link

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.

@TheCaptain1810
Copy link
Contributor

I'll fix this.

@gaearon
Copy link
Member

gaearon commented Feb 18, 2025

It’s not used for rendering so it’s not a problem. It’s not state in that sense.

@gaearon gaearon closed this as completed Feb 18, 2025
@behanprw
Copy link
Author

behanprw commented Feb 18, 2025

@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

@TheCaptain1810
Copy link
Contributor

@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.

@gaearon
Copy link
Member

gaearon commented Feb 18, 2025

There's no reason to store nextId in state because it is not used for rendering, and thus is not "state" in React sense of the word.

@TheCaptain1810
Copy link
Contributor

@gaearon exactly, understood! Thanks for the clarification!

@behanprw
Copy link
Author

Ok, thanks! @gaearon

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants