Site is currently on development mode

Immutable Updates in React and Redux

Last updated 2 years ago by Dave Ceddia


Immutability is kind of hard to wrap your head around at first. It seems like a paradox. Changing the data without changing the data? Huh?

On top of that, writing code to do immutable state updates is tricky. Below, you will find a few common patterns.

Try them out on your own, whether in the browser developer console or in a real app. Pay particular attention to the nested object updates, and practice those. I find those to be the trickiest.

All of this actually applies to React state too, so the things you learn in this guide will apply whether you use Redux or not.

Finally, I should mention that some of this code can become easier to write by using a library like Immutable.js, though it comes with its own tradeoffs. If you recoil at the syntax below, check out Immutable.js.

The Spread Operator

These examples make heavy use of the spread operator for arrays and objects. It’s represented by ... and when placed before an object or array, it unwraps the children within.

``` // For arrays: let nums = [1, 2, 3]; let newNums = [...nums]; // => [1, 2, 3] nums === newNums // => false! not the same array

// For objects: let person = { name: "Liz", age: 32 } let newPerson = {...person}; person === newPerson // => false! not the same object

// Internals are left alone: let company = { name: "Foo Corp", people: [ {name: "Joe"}, {name: "Alice"} ] } let newCompany = {}; newCompany === company // => false! not the same object newCompany.people === company.people // => true! ```

When used as shown above, the spread operator makes it easy to create a new object or array that contains the exact same contents as another one. This is useful for creating a copy of an object/array, and then overwriting specific properties that you need to change:

``` let liz = { name: "Liz", age: 32, location: { city: "Portland", state: "Oregon" }, pets: [ {type: "cat", name: "Redux"} ] }

// Make Liz one year older, while leaving everything // else the same: let olderLiz = { ...liz, age: 33 } ```

The spread operator for objects is a stage 3 draft, which means it’s not officially part of JS yet. You’ll need to use a transpiler like Babel to use it in your code. If you use Create React App, you can already use it.

Recipes for Updating State

These examples are written in the context of returning state from a Redux reducer: pretend that the state = {whatever} at the top is the state that was passed in to the reducer, and then the updated version is returned underneath.

Read full Article