DEV Community

Yu Hamada
Yu Hamada

Posted on

Understanding immutability for beginners in React

Table of contents

  1. At the beginning
  2. What is immutability?
  3. Why important?
  4. The example of immutable operations
    • Spread Syntax
    • Destructuring assignment
    • Array prototype method
  5. 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'}
Enter fullscreen mode Exit fullscreen mode

Destructuring assignment

const obj = { a: 1, b: 2 };
const newObj = { ...obj, b: 3 };
Enter fullscreen mode Exit fullscreen mode

Array prototype method

const newArray = oldArray.map(item => item * 2);
const filtered = oldArray.filter(item => item > 0);
const combined = [...oldArray1, ...oldArray2]; 
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)