What is Immutability

Joao Pedro Soares
2 min readJul 8, 2022

--

Immutability it's one of the most important concepts to learn in the React universe, and is used not only for it, immutability is actually one of the fundamentals of computing and is used in a lot of technologies, frameworks and programming languages.

The concept of immutability basics says that a variable should never have your value changed, it will ever RECEIVE a new value. When we say that a variable is immutable, it means that we can't change directly the value of that variable, we nee do GIVE a new value to it.

Let's think in an array of users:

users = ['user1', 'user2', 'user3']

If we need to add a new user to this list, we would do something like this:

users.push('newUser')

And that would works totally fine, at the end, our array would have our new user, but when you are using React and you do something like that, you throw away the benefits that immutability brings.

When the properties and state of the component are immutable objects or values, it's easier to organize the re-render process of your components, avoiding unnecessary renders.

If you are not familiar with concepts like props, state and components i recommend you read this:

In Javascript we have some ways to implement immutability, but two are the most used:

Object.assign

To create a new object with its old values and adding new ones, we can use Object.assign method.

Spread Operator

Spread operator allows us to quickly copy all or part of an existing array or object into another array or object.

For arrays:

For objects:

In React, the way we use to implement immutability is through the hook useState, if you wanna know more about it, i will leave a link below to help you (If you wanna know more only about the useState hook, go directly to the state section of the article).

I hope this article helped you somehow in your study of Immutability, any suggestion is welcome, thanks for your attention and never forget, don’t stop learning.

--

--