Reaction concept: immutability

What is immutability? And how does it fit in the React world?

When programming in React, one concept you may encounter is immutability (in contrast, mutability).

This is a controversial topic, but no matter how you think about the concept of immutability, React and the power of most of its ecosystem, you need to at least understand why it is so important and what it means.

In programming, if the value of a variable cannot be changed after creation, the variable is immutable.

You are already using immutable variables without knowing it when you manipulate strings. By default, strings are immutable, when you actually change them, you will create a new string and assign it to the same variable name.

Immutable variables can never be changed. To update its value, create a new variable.

The same is true for objects and arrays.

To add new items, not to change the array, but to create a new array by concatenating the old array and the new item.

The object is never updated, but it is copied before the object is changed.

This applies to React in many places.

For example, you should never changestateThe direct properties of the component, but only throughsetState()method.

inRedux, You will never change the state directly, but only through the reducer (ie function).

The question is, why?

There are many reasons, the most important of which are:

  • Mutations can be centralized, such as Redux, which can improve debugging capabilities and reduce error sources.
  • The code looks more concise and easy to understand. You never expect a function to change certain values without your knowledge, which gives youPredictability. When a function does not change the object but only returns a new object, it is called a pure function.
  • The library can optimize code because, for example, JavaScript is faster when replacing old object references with brand new objects instead of mutating existing objects. This for youwhich performed.

Download mine for freeResponse Handbook


More response tutorials: