React Developer interview question · Most asked
Why must React state be updated immutably, and how do you update nested state?
Summary
React decides whether to re-render by comparing references (Object.is). Mutating an object or array in place keeps the same reference, so React may skip updates and memoized components show stale data. Create new objects/arrays with spread, map, filter or structuredClone, or use Immer.
Longer Answer
Use functional updates (setItems(prev => ...)) when the new state depends on the previous one, especially with batching. Immer's produce lets you write 'mutating' code that produces immutable updates.
Code Example
setTodos((prev) => prev.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
setUser((prev) => ({ ...prev, address: { ...prev.address, city: "Berlin" } }));
Key Points
- Reference equality drives re-renders
- Spread/map/filter for new copies
- Functional updates for prev-dependent state
- Immer for deep updates
More most-asked React Developer questions
- Explain React concept: keys in lists.
- Explain React concept: unidirectional data flow.
- Explain React concept: controlled vs uncontrolled inputs.
- Explain React concept: state.
- Explain React concept: lifting state up.
- What does `useState` do and when should you use it?
- What does `useEffect` do and when should you use it?
- What does `useContext` do and when should you use it?