Under the Hood: Why React Needs Immutable State 👀
A second post, with other interesting information.
As a beginner, I also wonder why we need to create a new array or object when updating a state variable. Why can’t we mutate the current value variable?
As a beginner, I also wonder why we need to create a new array or object when updating a state variable. Why can’t we mutate the current value variable?
In this blog, I have shared a detailed view from my perspective on why React state changes have to be immutable.
How does React check for state updates?
So, here is the catch: React doesn’t check for values. Instead, React relies on a very cheap and fast check.
oldState === newState // shallow reference comparison
React uses references to detect changes ( objects and arrays in JavaScript are stored by reference )
const a = [1, 2];
const b = a; // b references the same array
If you mutate the array
a.push(3); // both a and b change
But the reference stays the same. So React sees this
previousState === nextState // true
React thinks nothing has changed, so it skips the re-render. That’s why we need to create a new copy of the array — to let React know that something has actually been updated. Never mutate React state (even when it seems to work)
- Create a new array/object
- Modify that new array/object
- Set the new array/object into the state.
Thanks for taking the time to read my blog.
I genuinely appreciate it. Concepts like immutability can seem small, but they shape how React actually works behind the scenes. ✌️
Image Gallery