Skip to content

React Concept: Immutability

FULL-STACK WEB DEVELOPMENT BOOTCAMP

2024 COHORT SIGNUPS END TOMORROW

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

One concept you will likely meet when programming in React is immutability (and its opposite, mutability).

Itโ€™s a controversial topic, but whatever you might think about the concept of immutability, React and most of its ecosystem kind of forces this, so you need to at least have a grasp of why itโ€™s so important and the implications of it.

In programming, a variable is immutable when its value cannot change after itโ€™s created.

You are already using immutable variables without knowing it when you manipulate a string. Strings are immutable by default, when you change them in reality you create a new string and assign it to the same variable name.

An immutable variable can never be changed. To update its value, you create a new variable.

The same applies to objects and arrays.

Instead of changing an array, to add a new item you create a new array by concatenating the old array, plus the new item.

An object is never updated, but copied before changing it.

This applies to React in many places.

For example, you should never mutate the state property of a component directly, but only through the setState() method.

In Redux, you never mutate the state directly, but only through reducers, which are functions.

The question is, why?

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

โ†’ Get my React Beginner's Handbook
โ†’ Read my full React Tutorial
  • Learn modern web development in my BOOTCAMP (SIGNUP END TOMORROW FEB 20, 2024)
  • THE VALLEY OF CODE (+ PRO), your web development manual
  • I wrote 15+ coding BOOKS, all available in THE VALLEY OF CODE PRO
  • Indie solopreneur internet business masterclass SOLO LAB (summer 2024)