Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 41 ยท Core Concepts

State and Immutability in Redux

Learn what belongs in Redux state, why you must never mutate it and how to copy objects, nested data and arrays safely with spread, map and filter. Live examples included.

The state in Redux is a single JavaScript value, almost always a plain object, that describes everything your app needs to remember. Redux imposes two rules on it: it should be made of plain, serializable data, and you must never change it in place. Instead, every update produces a new value, and the old one stays untouched.

That second rule is called immutability, and it is the one that trips up most beginners. This lesson shows why Redux needs it and gives you the copy patterns for objects, nested objects and arrays. Redux Toolkit later lets you write "mutating" code safely, but you must understand what it does for you.

What belongs in state

State should be:

  • Plain data: objects, arrays, strings, numbers, booleans, null. No class instances, functions, Map/Set, Promise or DOM nodes.
  • Serializable: JSON.stringify should work on it. This is what makes saving, restoring and DevTools replay possible.
  • Minimal: store the least you need and derive the rest. A list of items is state; the count of items is derived.
  • Normalised when it is a collection of records: prefer { byId: {...}, ids: [...] } to nested copies (covered in Combining Reducers and State Shape).
JavaScript
// A reasonable state shape
const state = {
  todos: { byId: { 1: { id: 1, text: 'Learn Redux', done: false } }, ids: [1] },
  filter: 'all',
  user: { id: 7, name: 'Ada' },
};

Why immutability matters

Redux and React-Redux decide whether something changed by comparing references with ===. If you change an object in place, its reference is the same, so "did it change?" answers "no" and nothing updates. A new object has a new reference, so the check is fast and reliable: no deep comparison of the whole tree.

Immutability also gives you predictable history (old states stay intact, so time travel works), safe debugging, and no surprise changes from distant code.

Run this to see the bug. A subscriber that watches a selected value fails to notice a mutation:

JS Mutation hides changes from === checks

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Copy patterns for objects

The spread operator { ...obj } makes a shallow copy. Later keys override earlier ones, so { ...user, age: 37 } is "the user, but with a new age". Copy every level on the path to the value you change; leave the rest alone, so unchanged parts keep the same reference.

JavaScript
const next = {
  ...state,                 // keep all other top-level keys
  user: {
    ...state.user,          // keep other user fields
    address: {
      ...state.user.address,
      city: 'Oslo',         // the one thing that changes
    },
  },
};

Only state, user and address get new references. Something like state.todos still points to the same array, which is what lets selectors on it skip work.

Copy patterns for arrays

Never use push, pop, splice, sort or reverse on state arrays (they mutate). Use these instead:

Goal Immutable code
Add to the end [...items, newItem]
Add to the start [newItem, ...items]
Remove by id items.filter((t) => t.id !== id)
Update one item items.map((t) => (t.id === id ? { ...t, done: true } : t))
Insert at index [...items.slice(0, i), item, ...items.slice(i)]
Sort [...items].sort(compare) or items.toSorted(compare)
Reverse items.toReversed()

toSorted, toReversed, toSpliced and with are modern, non-mutating array methods available in current browsers and Node 20+.

JS Immutable update recipes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last four lines show structural sharing: only the objects on the changed path are new. That is why immutable updates are cheap, even for large state.

Non-serializable values

Do not put these in the store: Date objects (store an ISO string or a number), Map and Set (store plain objects and arrays), class instances, functions, promises, File objects. They break JSON.stringify, persistence and replay, and Redux Toolkit's development checks will warn about them. If you need a date, store date.toISOString() or Date.now() and build the Date in the component.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does mutating state in place cause bugs in a Redux app?

    Redux and React-Redux compare references. A mutated object keeps its reference, so updates are skipped and old states are corrupted.
  2. 2. Which line adds a todo to state.items without mutating?

    Spreading the old array into a new one and adding the item creates a new array; the old one is untouched.
  3. 3. After updating state.user.address.city immutably, which objects get new references?

    Every object on the path from the root to the changed value is copied. Siblings such as state.items are reused.
  4. 4. Which value should NOT be stored in Redux state?

    State should be plain, serializable data. Class instances break serialization, persistence and DevTools replay.

Summary

  • Redux state is plain, serializable, minimal data.
  • Never mutate it; return new objects and arrays and copy every level on the path to the change.
  • Use spread, map, filter and non-mutating array methods; avoid push, splice, sort in place.
  • Unchanged parts keep their references (structural sharing), which keeps comparisons cheap.
  • Redux Toolkit's Immer lets you write mutating-looking code that produces these immutable updates.

Next: Actions and Action Creators