Understanding immutability for beginners in React
Yu Hamada
Posted on May 19, 2024
Table of contents
- At the beginning
- What is immutability?
- Why important?
- The example of immutable operations
- Spread Syntax
- Destructuring assignment
- Array prototype method
- Conclusion
At the beginning
While I'm studying React, I frequently came across the word "immutability" but didn't look into it deeply because it sounded hard to know. However, I want to gain a thorough understanding of it by writing this article.
What is immutability?
Immutability in React means that we should not modify the existing state or props directly. Instead, we should create a new copy of the state or props with the desired changes.
Why do we need immutability?
React detects changes in components by checking the difference of objects. This is done for performance reasons and to make re-rendering more predictable.
If you perform mutable operations, the original information is also changed. This means React cannot detect the difference between the state before and after the change.
On the other hand, in case of immutable operations, React can detect the difference because the state before and after the change is referenced separately. Additionally, since the original state is not changed, it can be kept as a history, allowing for features like undoing changes up to a certain point.
Performing immutable operations ensures that React can accurately detect changes and provides benefits like maintaining a history of state changes, which allows for more predictable rendering and additional functionality.
The example of immutable operations
Spread Syntax
// update array
const newArray = [...oldArray, newItem];
// update object
const newObj = {...oldObj, newProp: 'value'}
Destructuring assignment
const obj = { a: 1, b: 2 };
const newObj = { ...obj, b: 3 };
Array prototype method
const newArray = oldArray.map(item => item * 2);
const filtered = oldArray.filter(item => item > 0);
const combined = [...oldArray1, ...oldArray2];
Conclusion
Immutability in React provides performance benefits, prevents bugs from unexpected mutations, and makes code easier to reason about. It's a core principle React developers should follow.
Posted on May 19, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.