useState: State Management
Most state bugs are architecture bugs: duplicated source of truth, incorrect ownership, and mutation patterns that break referential assumptions.
Quick Navigation: State Ownership Mental Model • Update Semantics and Edge Cases • Trade-offs and Interview Takeaway
Quick Decision Guide
useState gives local state with snapshot semantics and scheduled updates.
- Reads are from current render snapshot - Writes schedule future renders - Functional updates avoid stale closure bugs
Interview signal: Discuss state ownership and update fan-out, not just setter syntax.
State Ownership Mental Model
🔥 Insight
State location defines performance boundaries.
🧠 Mental Model
Update Semantics and Edge Cases
Pattern 1: Functional Updates
Use when state depends on previous state:
// ❌ WRONG - Stale closure
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1); // May use stale value
setCount(count + 1); // Still uses stale value
};
// ✅ CORRECT - Functional update
const increment = () => {
setCount(prev => prev + 1);
setCount(prev => prev + 1); // Uses latest value
};Pattern 2: Object State
Update objects immutably:
const [user, setUser] = useState({ name: '', age: 0 });
// ✅ CORRECT - Immutable update
setUser(prev => ({ ...prev, name: 'John' }));Edge Cases
Rules of Hooks (and why)
These rules follow from React's render model:
Trade-offs and Interview Takeaway
Trade-offs
🎯 Interview Takeaway
Strong answer: choose state owner intentionally, prefer derivation, and use functional updates when next state depends on previous state.