Updating State and Immutable Updates
Updating State and Immutable Updates
1. The Rule of Immutability
In React, state should be treated as immutable (read-only). You must never modify existing state objects or arrays directly in place. Instead, always replace them with a fresh copy containing the desired changes.
Because React uses reference equality (Object.is) to detect state changes, mutating an existing object or array in place preserves the same memory address. React assumes nothing has changed and bails out of re-rendering.
2. Functional State Updates (Updater Functions)
State updates are batched and asynchronous. If your new state depends on the immediately preceding state, you should pass a callback function to your state setter instead of a raw value:
3. Immutably Updating Arrays in State
Arrays in JavaScript are reference types. When adding, removing, or modifying array elements in state, use non-mutating array methods:
| Action | ❌ Mutating (Avoid) | ✅ Immutable (Preferred) |
|---|---|---|
| Add item | arr.push(item), arr.unshift(item) | [...arr, item] or [item, ...arr] |
| Remove item | arr.splice(index, 1), arr.pop() | arr.filter(item => item.id !== id) |
| Update item | arr[index] = newValue | arr.map(item => item.id === id ? { ...item, ...newValue } : item) |
| Sort / Reverse | arr.sort(), arr.reverse() | [...arr].sort(), [...arr].reverse() |
Concrete Array Update Examples:
4. Immutably Updating Nested Objects
When updating nested objects, remember that the object spread operator (...) only performs a shallow copy. Nested objects must be explicitly copied at every level of depth:
Practice Quiz
user.name = 'New'; setUser(user);) often fail to trigger a re-render?setCount(prev => prev + 1)) to a state setter?...) when copying objects with nested properties?Lifting State Up Between Siblings
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| The useState Hook Fundamentals | Lifting State Up Between Siblings |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.