React Concept: Immutability
By Flavio
Published · Updated
Tagged: React
Understand what immutability means in React, why you never mutate state directly but copy it instead, and how it gives you predictability and performance.
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 state directly. You call the setter you get from useState and pass it a new object or array. See how to update an object in state.
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:
- Mutations can be centralized, like in the case of Redux, which improves your debugging capabilities and reduces sources of errors.
- Code looks cleaner and simpler to understand. You never expect a function to change some value without you knowing, which gives you predictability. When a function does not mutate objects but just returns a new object, it’s called a pure function.
- React can check for changes very fast. If you never mutate, a new value means a new object, so React only has to compare references (
prevObj === obj) instead of looking at every property. That’s howmemoand other optimizations skip work. This gives you performance. - Features like undo/redo or a change history are easy, because the old versions of your data are still there, untouched.
Why mutating state doesn’t update the screen
This is the bug you’ll meet first:
const [position, setPosition] = useState({ x: 0, y: 0 })
function handleMove(e) {
position.x = e.clientX // 🚩 mutates the current state
position.y = e.clientY
setPosition(position) // 🚩 nothing happens
}
React compares the new state with the old one using Object.is. It’s the same object, so React thinks nothing changed and skips the re-render.
Pass a new object instead:
function handleMove(e) {
setPosition({
x: e.clientX,
y: e.clientY,
})
}
Copying objects
To change one property and keep the rest, copy the object with the spread syntax and override what changes:
setPerson({
...person,
firstName: 'Roger',
})
The spread is shallow: it copies only one level. For a nested object, you copy each level you go through:
setPerson({
...person,
address: {
...person.address,
city: 'Bologna',
},
})
Copying arrays
Many array methods change the array in place. With state, use the ones that return a new array:
| To | Avoid (mutates) | Use (returns a new array) |
|---|---|---|
| add | push(), unshift() | [...arr, item], concat() |
| remove | pop(), shift(), splice() | filter(), slice() |
| replace | splice(), arr[i] = x | map() |
| sort | sort(), reverse() | toSorted(), toReversed(), or copy first |
Some examples:
// add
setTodos([...todos, newTodo])
// remove
setTodos(todos.filter(t => t.id !== id))
// update one item
setTodos(todos.map(t => (t.id === id ? { ...t, done: true } : t)))
// sort
setTodos(todos.toSorted((a, b) => a.title.localeCompare(b.title)))
Watch out for slice() and splice(). They look alike, but slice() returns a copy and splice() changes the original. toSorted(), toReversed(), toSpliced() and with() are newer methods that return a copy. I wrote about them in JavaScript immutable array methods.
The shallow copy trap
Copying an array doesn’t copy the objects inside it:
const next = [...todos]
next[0].done = true // 🚩 this also changes todos[0]
setTodos(next)
next[0] and todos[0] are the same object. Use map() and create a new object for the item you change, like in the “update one item” example above.
Also, const doesn’t make anything immutable. const todos = [] only stops you from reassigning todos. You can still push() into it.
Immer, if the copying gets painful
With deeply nested state, all those spreads get hard to read. Immer lets you write code that looks like a mutation on a draft, and it produces a new object for you. The use-immer package gives you a useImmer hook:
import { useImmer } from 'use-immer'
const [todos, updateTodos] = useImmer(initialTodos)
function toggle(id) {
updateTodos(draft => {
const todo = draft.find(t => t.id === id)
todo.done = !todo.done
})
}
Redux Toolkit uses Immer too, which is why you can write state.value += 1 in its reducers.
Want me to talk about your product? You can sponsor this site.