Should the `state` object be modified directly?
See original GitHub issueI remember watching some Dan Abramov video about redux or something, and there was a bit about not mutating the state, but always returning a copy of it.
So I’m doing this in my app:
return Object.assign(state, {selectedIndex: --state.selectedIndex})
But should I just be modifying the state directly? Does it matter?
state.selectedIndex--
return state
Issue Analytics
- State:
- Created 7 years ago
- Comments:8 (5 by maintainers)
Top Results From Across the Web
Why Not To Modify React State Directly - Dave Ceddia
Everyone (and the React docs) say not to mutate state directly. Here's a live example of what happens when you do.
Read more >Why can't I directly modify a component's state, really?
This answer is to provide enough information to not change/mutate the state directly in React. React follows Unidirectional Data Flow.
Read more >Why we should never update React State directly! - Medium
So, React won't be able to see that there is a change of the state and so it won't be reflected in the...
Read more >Updating Objects in State - React Docs
State can hold any kind of JavaScript value, including objects. But you shouldn't change objects that you hold in the React state directly....
Read more >How to accidentally mutate state. And why not to
When you learn about React and state you will often read this: "Don't mutate the state". This means you shouldn't change an object...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Sorry @yoshuawuyts but I don’t fully understand your explanation.
Does this mean the
state
argument I receive in the reducer function is actually a copy of the “real” state object? In other words, what is the first argument toxtend
“under the hood”?What exactly is being frozen? It must not be the
state
argument, as it appears that I can make changes to that directly without anything breaking. From the demo:Can be changed to this and everything works:
I also tried adding
use strict
for grins and didn’t see any exceptions.What does this mean?
I’m basically asking for clarification on everything you just said! 🙈
Once I see the light, I will try to make it worth your while by opening a PR with some helpful documentation on this topic.
Sine objects are passed by refernce it matters. If you touch the state object you’ll have side effects. Which is against the functional programming/Redux philosophy.