HomeReact
Chapter 7

07 — useState & useReducer

Deep dive into React's two primary state management hooks. useState for simple state, useReducer for complex state logic.

useState Deep Patterns

PatternExample
Lazy initializationuseState(() => expensiveCalc()) — runs only once
Updater functionsetState(prev => prev + 1) — avoids stale closures
Object statesetState(prev => ({ ...prev, key: value }))
Array statesetState(prev => [...prev, newItem])
Reset statesetState(initialValue) or use a key prop

useReducer

const [state, dispatch] = useReducer(reducer, initialState);
ConceptDescription
StateThe current state value
ActionAn object describing what happened { type: 'INCREMENT' }
DispatchFunction to send an action
ReducerPure function: (state, action) => newState

useState vs useReducer

useStateuseReducer
Best forIndependent values, simple updatesRelated values, complex transitions
Update logicInline in handlerCentralized in reducer
DebuggingHarder (scattered)Easier (one function)
TestingNeeds componentReducer is a pure function

File

  • state-hooks.tsx — lazy init, updater patterns, useReducer with actions, todo app, complex form, when to use which