Hooks & APIs: useState vs. useReducer
useState & useReducer: Choose the right primitive for simple state versus complex state transitions.
In React, component state represents how the user interface should look and behave at any given point in time. React provides two core hooks for declaring and managing local component state: useState and useReducer.
Under the hood, useState is actually implemented on top of useReducer within React’s Fiber reconciler. Despite sharing the same operational mechanics, they serve two distinct architectural roles:
- useState is optimized for isolated, independent values where state transitions are straightforward assignments or functional derivations.
- useReducer is optimized for complex, interdependent state machines where a single event ("action") triggers coordinated updates across multiple fields.
## 1. Architectural Comparison
| Dimension | useState | useReducer |
| --- | --- | --- |
| Mental Model | "Set state directly to this new value." | "An event occurred; let the reducer decide the next state." |
| Logic Placement | Inline inside event handlers and component effects. | Centralized, pure reducer function isolated from the UI layer. |
| Field Interdependence | Manages fields in silos; coordinating multiple values requires multiple updates. | Manages composite objects where updating field A depends on or resets field B. |
| Dispatcher Identity | State setter (setX) maintains a stable identity across renders. | Action dispatcher (dispatch) maintains a stable identity across renders. |
| Testability | Requires mounting the component and firing user interaction events. | Pure function logic testable via plain unit tests without DOM scaffolding. |
| Prop Drilling Optimization | Passing multiple individual setters creates prop bloat across deep trees. | Passing a single dispatch function down (or via Context) avoids callback proliferation. |
## 2. Deep Dive: useState
useState declares a state variable that persists between render cycles.
### 2.1 Direct Assignment vs. Functional Updates
Choosing between a raw value and an updater callback prevents race conditions and stale closure traps:
```ts
// 1. Direct Assignment: Value does NOT depend on previous state
setName('Aarav');
// 2. Functional Updater: Next state depends on previous state
setCount(prevCount => prevCount + 1);
```
Why Functional Updaters Matter (Concurrency & Batched Updates)
React batches state updates inside event handlers, promises, and timeouts. If you invoke multiple direct updates within the same execution frame, each call captures the stale count variable from the current render closure:
```ts
function handleTripleClick() {
// If count starts at 0:
setCount(count + 1); // Reads count = 0 -> schedules count = 1
setCount(count + 1); // Reads count = 0 -> schedules count = 1
setCount(count + 1); // Reads count = 0 -> schedules count = 1
// Final committed state: 1 (NOT 3!)
}
function handleTripleClickSafe() {
// Updaters are queued and evaluated sequentially by the reconciler:
setCount(prev => prev + 1); // 0 -> 1
setCount(prev => prev + 1); // 1 -> 2
setCount(prev => prev + 1); // 2 -> 3
// Final committed state: 3
}
```
### 2.2 Lazy State Initialization
If calculating the initial state requires disk I/O, localStorage access, complex math, or parsing large arrays, passing the expression directly executes that expensive operation on every single render pass, even though React only consumes the result on initial mount:
```ts
// ❌ ANTI-PATTERN: Runs JSON.parse on EVERY render!
const [config, setConfig] = useState(
JSON.parse(localStorage.getItem('app_config') || '{}')
);
// ✅ CORRECT: Lazy Initializer Function
// React invokes this callback ONCE during initial mount
const [config, setConfig] = useState(() => {
try {
const raw = localStorage.getItem('app_config');
return raw ? JSON.parse(raw) : { theme: 'dark', sound: true };
} catch {
return { theme: 'dark', sound: true };
}
});
```
## 3. Deep Dive: useReducer
useReducer decouples what happened (actions) from how the state updates (the reducer). It models state transitions as a pure mathematical function:
- $$(\text\{prevState\}, \text\{action\}) \implies \text\{nextState\}$$
### 3.1 Managing Interdependent State & Avoiding Impossible States
Consider a network request lifecycle. A naive implementation using useState scatters related values:
```ts
// ❌ FRAGILE: Multiple disjoint state variables risk impossible states
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
async function fetchData() {
setIsLoading(true);
try {
const res = await api.getUsers();
setData(res);
// Easy to forget:
// setError(null);
} catch (err) {
setError(err);
// Potential bug: old data remains in state alongside the error
} finally {
setIsLoading(false);
}
}
```
An unexpected execution sequence or missed setter can trap the UI in an impossible state: isLoading: true while error: 'Failed' and data: [...] simultaneously coexist.
### 3.2 The useReducer Solution with Discriminated Unions
Pairing useReducer with TypeScript discriminated unions guarantees that state transitions are deterministic and mutually exclusive:
```ts
interface FetchState {
status: 'idle' | 'loading' | 'success' | 'error';
data: T | null;
error: string | null;
}
type FetchAction =
| { type: 'FETCH_START' }
| { type: 'FETCH_SUCCESS'; payload: T }
| { type: 'FETCH_FAILURE'; error: string }
| { type: 'RESET' };
function fetchReducer(
state: FetchState,
action: FetchAction
): FetchState {
switch (action.type) {
case 'FETCH_START':
return { status: 'loading', data: null, error: null };
case 'FETCH_SUCCESS':
return { status: 'success', data: action.payload, error: null };
case 'FETCH_FAILURE':
return { status: 'error', data: null, error: action.error };
case 'RESET':
return { status: 'idle', data: null, error: null };
default: {
const _exhaustiveCheck: never = action;
return state;
}
}
}
```
### Consuming the Reducer inside a Component
```ts
import { useReducer, useEffect } from 'react';
const initialState: FetchState = {
status: 'idle',
data: null,
error: null,
};
export function UserDirectory() {
const [state, dispatch] = useReducer(fetchReducer, initialState);
useEffect(() => {
let ignore = false;
dispatch({ type: 'FETCH_START' });
fetch('/api/users')
.then(res => res.json())
.then(data => {
if (!ignore) dispatch({ type: 'FETCH_SUCCESS', payload: data });
})
.catch(err => {
if (!ignore) dispatch({ type: 'FETCH_FAILURE', error: err.message });
});
return () => { ignore = true; };
}, []);
if (state.status === 'loading') return = {
status: 'idle',
data: ['old-item'],
error: 'previous-error'
};
const nextState = fetchReducer(prevState, { type: 'FETCH_START' });
expect(nextState).toEqual({
status: 'loading',
data: null,
error: null
});
});
});
```
Loading users...
; if (state.status === 'error') return{state.error}
; if (!state.data) return null; return (-
{state.data.map(user =>
- {user.name} )}
