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.
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:
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() |
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:
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?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| The useState Hook Fundamentals | Lifting State Up Between Siblings |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.