DEV Community

Ryota Murakami
Ryota Murakami

Posted on

What the benefit immutable on the state management?

Many React forks has interested immutable like Immer but I don't understand what the benefit immutable on the state management.

Alt Text

Application state is fundamentally mutable for handle user interaction etc.

I guess some forks using immutable solution without technical reason like cargo cult.
But I want to know those certainly use cases, so I'm glad to feel free comment your usage if any immutable solution user read this article! πŸ€—

Top comments (10)

Collapse
 
jannikwempe profile image
Jannik Wempe • Edited

Between rerendering the page or parts of it (in react it's called reconciliation phase) the previous state will be compared to the new state to check if updates are required. Now check the following example why it is useful to change the state immutable:

const oldState = ["apple", "banana", "orange"];

// mutable
oldState[0] = "tomato";
const newState = oldState;
oldState === newState; // true - even with different content

// or immutable
const updatedState = [...oldState];
updatedState[0] = "tomato";
const newState = updatedState;
oldState === newState; // false

By changing the state mutable, the actual content of the state has to be compared, which could be a huge performance cost. So all comes down to performance in the end.

EDIT: You can check this great article on LogRocket (see "Performance optimizations in React").

Collapse
 
daniel13rady profile image
Daniel Brady • Edited

Hmm, I think your example here might be misleading. If you remove the array mutation from both of your examples, you get the same results:

const oldState = ["apple", "banana", "orange"];

// mutable
/* oldState[0] = "tomato"; */
const newState = oldState;
oldState === newState; // true 

// or immutable
const updatedState = [...oldState];
/* updatedState[0] = "tomato"; */
const newState = updatedState;
oldState === newState; // false

The strict equality comparator, ===, does a simple pointer comparison when working with objects and arrays (or "object identity" comparison, if you prefer).

In the 'mutable' example, oldState === newState is true because they reference the same object: newState points to oldState, which points to an array. Array equality, as I think you allude to, does not look at contents.

In the 'immutable' example, oldState === newState is false because they are not the same object: you've made a copy, so newState points to an array and oldState points to a different array. Again, the equality comparison doesn't care about the contents, only the pointer.

With this in mind, Jannik, does your statement about the performance impact still hold true?

At least on the surface, it seems like the approach you've labeled "immutable" here would be less performant because you're copying the original array instead of reusing it. πŸ€” But I'm honestly not familiar with JS performance traits, curious of your thoughts.

Collapse
 
jannikwempe profile image
Jannik Wempe • Edited

In my opinion you added the missing explanation to my comment πŸ˜‰

The first one is mutable because objects (same with arrays and functions) are reference types and therefore changing one variable will also change the other (both pointing to the same object).

You are right, the copying itself is slower than just pointing to the same object. But to compare the oldState and the newState in the "mutable-way" you would have to compare all the values in the object/array and that can be much slower than the copying (just imagine a deeply nested object, eg. cart.products.apple.prices.eur).

Maybe in this example the copying could be slower than the comparison of the values due to the small array.

EDIT:
Just did a quick comparison in performance:

let oldState = ["apple", "banana", "orange"];
let newState;

let DOMHasToUpdate = false; // has to update if old and new state are different
console.time("mutable");
for (let i=0;i<1000000;i++) {
    newState = oldState;
    DOMHasToUpdate = oldState.map((el, idx) => el === newState[idx]).includes(false);
}
console.timeEnd("mutable");

console.time("immutable");
for (let i=0;i<1000000;i++) {
    newState = [...oldState];
    DOMHasToUpdate = !newState === oldState;
}
console.timeEnd("immutable");

// OUTPUT:
// mutable: 39.876953125ms
// immutable: 21.088134765625ms

I know here is no actual change in the state and changing the newState in the mutable way would also lead to an update of the oldState but it is more about the performance for copying vs. comparing values.

But yes, I think my point regarding performance still holds true.

Thread Thread
 
malloc007 profile image
Ryota Murakami

Thank you for your meaningful input with @dabrady 😎
I imagined rough mind model about last perfomance comparison mutable like "full-scan", immutable like "check book cover".

That is not correct strictly, but I got a chance re-learning around JavaScript's Logical Comparison! 🀩🍺

Thread Thread
 
daniel13rady profile image
Daniel Brady

I imagined rough mind model about last perfomance comparison mutable like "full-scan", immutable like "check book cover".

That's a really nice mental model 😍

Collapse
 
malloc007 profile image
Ryota Murakami

Thank you for your qualified comment!

I got it immutable version cut off garbage reference that might cause unexpected change, so I think immutable version bring confidence and to be impossible above mutable situation, really clear. πŸ˜€

And I could notice context about why many people using immutable solution your code example. πŸ‘¨β€πŸ’»

I really appreciate you and I also planing try LogRocket in latest project thanks sharing blog! πŸ€—

Collapse
 
patryktech profile image
Patryk

I use Vue, not React, but one more reason to use immutable state is to prevent unexpected side-effects.

If you have many computed properties, and you change the base object that a number of them depend on in one component, it may affect other components in ways you didn't expect. I believe Vue raises an error if you try to modify Vuex state outside of mutations.

If your component modifies the state only in its own copy of an object, the changes are localized and there are no far-reaching side effects, which helps prevent some bugs.

Collapse
 
malloc007 profile image
Ryota Murakami

Thank you for your Vue perspective, my last vue experience is at the 2015 DX
So I'm glad to know 2020's Vue Dev perspective 🀩

And I agree with last your last paragraph, thank you! πŸ˜„

Collapse
 
steelwolf180 profile image
Max Ong Zong Bao

I think it is used to prevent any unexpected circumstance to change the value, type or state of a variable. Think in terms API keys, tokens, hash.

Besides the benefit of it is that it has a faster read or access time for it

Collapse
 
malloc007 profile image
Ryota Murakami

Thank you comment your opinion, that seems legit! πŸ€—