Sub topic 3
Lazy initial state
Assume you know JavaScript functions, objects, arrays, JSX, props, and useState. This chapter focuses on reducer features that become useful as state grows.
Lazy initial state
useReducer accepts an optional third argument, an initializer function. React calls it with the second argument to calculate the initial state:
function init(initialCount) {
return { count: initialCount };
}
function reducer(state, action) {
switch (action.type) {
case 'incremented':
return { count: state.count + 1 };
case 'reset':
return init(action.payload);
default:
throw Error('Unknown action: ' + action.type);
}
}
const [state, dispatch] = useReducer(reducer, initialCount, init);Lazy initialization is useful when creating state requires work, such as parsing saved data. The initializer runs during initialization, not on every dispatch.
Modeling async work
Represent related request values as one state machine. A state machine is a fixed set of states and transitions.
| Status | Meaning |
|---|---|
| `idle` | No request has started |
| `loading` | A request is running |
| `success` or `error` | The request finished |
Use an effect for the request and a pure reducer for state transitions:
function reducer(state, action) {
switch (action.type) {
case 'started':
return { status: 'loading', data: null, error: null };
case 'succeeded':
return { status: 'success', data: action.data, error: null };
case 'failed':
return { status: 'error', data: null, error: action.error };
default:
throw Error('Unknown action: ' + action.type);
}
}Dispatch behavior
The dispatch function has a stable identity, so it is safe to omit from effect dependencies. React batches several updates triggered by the same event before rendering. If the reducer returns the identical state object, React can bail out of a re-render. Return a new object whenever state changed.
Passing state and dispatch through context
Context lets distant components read state without receiving it through every intermediate component. Use separate contexts for state and dispatch when components that only dispatch should avoid updates caused by state changes.
Testing and typing reducers
A reducer is a plain function, so test it without rendering a component:
const before = [];
const after = todosReducer(before, {
type: 'added',
id: 1,
text: 'Test'
});Assert that after is correct and before is unchanged. In TypeScript, a discriminated union connects each action’s type to its payload:
type Action =
| { type: 'incremented' }
| { type: 'set'; value: number };A switch on action.type then narrows the available fields and rejects invalid dispatch calls.
Exercise
Why should a reducer return a new object after a state change?
Show answer
React uses object identity to detect whether state changed. A new object makes the change visible and allows React to render the update.