Reducers for Complex Transitions
Worked example: turn a tangled upload queue into one typed reducer with an exhaustive switch, pure updates and Vitest unit tests that never render a component.
Contentsand lesson path
On this page
- The problem
- Step 1: name the states and the transitions
- Step 2: typed actions and the reducer
- Step 3: unit-test the transitions, no React needed
- Step 4: put it on screen
- Check your understanding
- Apply it
- Review prompt
Lessons of Frontend State Management
- Where Should This State Live? Concept · 20 min
- Reducers for Complex Transitions Worked example · 25 min
- Context Without the Re-render Tax Concept · 20 min
- External Stores and Selectors Worked example · 25 min
- Lab: Untangle a Prop-Drilled Cart Lab · 30 min
- Check: State Placement Scenarios Knowledge check · 6 questions
What you will learn
- Model complex state transitions with useReducer and typed actions, and share them through context without unnecessary re-renders.
Prerequisites: React Components & State
01. The problem
A file-upload queue looks harmless until the states multiply. Each file can be waiting, uploading, done or failed; only one may upload at a time; progress events arrive faster than the user can click; a failed file can be retried. Held as loose useState pieces — progressById, activeId, errorById, booleans to tell them apart — the update rules end up smeared across every handler, and two handlers racing on the same tick is how states that cannot co-exist end up co-existing.
This is the signature of state that wants a reducer: the next value depends on the current one and on which of several events happened. A reducer is one pure function — (state, action) => state — that holds every transition in one inspectable place. The packing-list lesson used useState for single independent values; this worked example builds the upload queue with useReducer and TypeScript doing the bookkeeping.
A rule of thumb for the threshold: useState fits values that change independently — a draft, a checkbox, an open flag. When a second value exists mainly to stay consistent with the first, or when several events must be interpreted against the same current state, a reducer pays for itself. The queue below crosses that line three times over.
02. Step 1: name the states and the transitions
status entered by leaves to
queued enqueue uploading (startNext)
uploading startNext done (completed), failed (failed)
done completed -
failed failed queued (retry)Writing the table before the code settles two disputes early. First, every file is in exactly one status — no isUploading and hasError booleans that can both be true. Second, the transitions are closed: if an event is not on this table, the reducer ignores it, and a status can never be reached by accident. One extra rule needs a home: startNext picks the first queued file and stores its id in activeId, and only one file may be active, so a second startNext while one runs changes nothing.
03. Step 2: typed actions and the reducer
export type UploadStatus = 'queued' | 'uploading' | 'done' | 'failed';
export type Upload = {
id: string;
name: string;
status: UploadStatus;
progress: number;
error?: string;
};
export type UploadState = { uploads: Upload[]; activeId: string | null };
export const initialUploads: UploadState = { uploads: [], activeId: null };
export type UploadAction =
| { type: 'enqueue'; id: string; name: string }
| { type: 'progress'; id: string; percent: number }
| { type: 'completed'; id: string }
| { type: 'failed'; id: string; error: string }
| { type: 'retry'; id: string }
| { type: 'startNext' };The action type is a discriminated union — the same shape as the literal unions in the TypeScript lessons, with type as the discriminant. Two payoffs arrive immediately. Inside a case 'progress', TypeScript narrows the action and action.percent type-checks without any cast. And an unhandled member of the union is a compile error rather than a silent afternoon of debugging, as the default branch below makes explicit.
export function uploadsReducer(
state: UploadState,
action: UploadAction,
): UploadState {
switch (action.type) {
case 'enqueue': {
const upload: Upload = {
id: action.id,
name: action.name,
status: 'queued',
progress: 0,
};
return { ...state, uploads: [...state.uploads, upload] };
}
case 'progress':
return mapUpload(state, action.id, (u) => {
if (u.status !== 'uploading') return u;
return {
...u,
progress: Math.max(u.progress, action.percent),
};
});
case 'completed':
return finishUpload(state, action.id, (u) => {
if (u.status !== 'uploading') return u;
return {
...u,
status: 'done',
progress: 100,
};
});
case 'failed':
return finishUpload(state, action.id, (u) => {
if (u.status !== 'uploading') return u;
return {
...u,
status: 'failed',
error: action.error,
};
});
case 'retry':
return mapUpload(state, action.id, (u) => {
if (u.status !== 'failed') return u;
return {
...u,
status: 'queued',
progress: 0,
error: undefined,
};
});
case 'startNext': {
const next = state.uploads.find((u) => u.status === 'queued');
if (!next || state.activeId) return state;
return {
...state,
activeId: next.id,
uploads: state.uploads.map((u) =>
u.id === next.id ? { ...u, status: 'uploading' } : u,
),
};
}
default: {
const unhandled: never = action;
throw new Error(`unknown action ${JSON.stringify(unhandled)}`);
}
}
}function mapUpload(
state: UploadState,
id: string,
update: (upload: Upload) => Upload,
): UploadState {
return {
...state,
uploads: state.uploads.map((u) => (u.id === id ? update(u) : u)),
};
}
function finishUpload(
state: UploadState,
id: string,
update: (upload: Upload) => Upload,
): UploadState {
const next = mapUpload(state, id, update);
// A finished upload frees the slot, so startNext may pick the next one.
return { ...next, activeId: next.activeId === id ? null : next.activeId };
}Every branch does the same three things: spread the old state, build the new one, return it. Nothing is edited in place, because React decides whether anything changed by comparing references with Object.is — push into an array and hand back the same object, and the update silently disappears. Nothing happens either: no fetch, no timer, no log line. Reducers must be pure functions of (state, action), for two reasons. React may call a reducer twice in development to surface impurities, so a reducer that sent a request would send it twice. And purity is what makes step 4 possible: the whole machine can be exercised without a single component. Do not count on the linter to catch a slip: the React Compiler lint rule react-hooks/immutability reports mutations it can see during render, but state.uploads.push(...) inside a reducer was not reported when this was tried with eslint-plugin-react-hooks 7.1.1, so the silent no-update failure stays your responsibility. Side effects belong at the dispatch site: in an event handler or an effect that dispatches progress as events arrive.
04. Step 3: unit-test the transitions, no React needed
import { describe, expect, it } from 'vitest';
import { initialUploads, uploadsReducer } from './uploads';
describe('uploadsReducer', () => {
it('starts only one upload at a time', () => {
let state = initialUploads;
state = uploadsReducer(state, { type: 'enqueue', id: 'u1', name: 'a.png' });
state = uploadsReducer(state, { type: 'enqueue', id: 'u2', name: 'b.png' });
state = uploadsReducer(state, { type: 'startNext' });
state = uploadsReducer(state, { type: 'startNext' });
expect(state.activeId).toBe('u1');
expect(state.uploads.find((u) => u.id === 'u2')?.status).toBe('queued');
});
it('frees the active slot when an upload finishes', () => {
let state = initialUploads;
state = uploadsReducer(state, { type: 'enqueue', id: 'u1', name: 'a.png' });
state = uploadsReducer(state, { type: 'startNext' });
state = uploadsReducer(state, { type: 'completed', id: 'u1' });
expect(state.activeId).toBe(null);
});
it('ignores late progress events after completion', () => {
let state = initialUploads;
state = uploadsReducer(state, { type: 'enqueue', id: 'u1', name: 'a.png' });
state = uploadsReducer(state, { type: 'startNext' });
state = uploadsReducer(state, { type: 'completed', id: 'u1' });
state = uploadsReducer(state, { type: 'progress', id: 'u1', percent: 60 });
const item = state.uploads.find((u) => u.id === 'u1');
expect(item?.status).toBe('done');
expect(item?.progress).toBe(100);
});
it('retries only failed uploads', () => {
let state = initialUploads;
state = uploadsReducer(state, { type: 'enqueue', id: 'u1', name: 'a.png' });
state = uploadsReducer(state, { type: 'startNext' });
state = uploadsReducer(state, { type: 'failed', id: 'u1', error: 'offline' });
state = uploadsReducer(state, { type: 'retry', id: 'u1' });
const item = state.uploads.find((u) => u.id === 'u1');
expect(item?.status).toBe('queued');
expect(item?.error).toBe(undefined);
});
}); Test Files 1 passed (1)
Tests 4 passed (4)This is the quiet superpower of reducers: the entire transition logic — including the awkward cases, a second startNext, progress that arrives out of order, and retrying only from a failed state — is testable in plain TypeScript, with no renderer, no fake timers and no DOM. All four transitions pass cleanly in the test suite above. The runtime shows its teeth too: the default branch throws on an unknown action, and the never assignment means a new action added to the union without a matching case fails to compile before any test runs.
05. Step 4: put it on screen
import { useReducer } from 'react';
import { initialUploads, uploadsReducer } from './uploads';
export function UploadQueue() {
const [state, dispatch] = useReducer(uploadsReducer, initialUploads);
return (
<section aria-label="Upload queue">
<ul>
{state.uploads.map((u) => (
<li key={u.id}>
{u.name}: {u.status} {u.progress}%
{u.error ? ` (${u.error})` : ''}
</li>
))}
</ul>
<p>Active: {state.activeId ?? 'none'}</p>
</section>
);
}The component is now thin: hold the state with useReducer, render it, dispatch on events. Add buttons that dispatch the actions above and click through a short scenario — enqueue two files, start one and complete it, start the other and fail it with network down, then retry it — and the list reads a.png: done 100% and b.png: failed 0% (network down), then after the retry b.png: queued 0% with Active: none. That sequence was checked by driving such buttons under Testing Library. Every list item is keyed by the file id, and the status text means the queue is announced as text, not conveyed by colour alone.
06. Check your understanding
07. Apply it
Take one piece of state in your own work that uses two or more booleans to describe itself, and redo this exercise end to end: draw the machine (statuses, events, illegal states), write the discriminated union, implement the reducer, and test three transitions — including one awkward one — in plain Vitest before any component renders it. The practice brief asks for exactly this treatment of the cart reducer, with unit tests; the lab does the cart step by step. Sharing comes next: context without the re-render tax shows how to hand the reducer's state and dispatch to distant components.
08. Review prompt
Without looking back: draw the upload queue machine from memory (four statuses, six events). Then explain what the never in the default branch buys at compile time, why the reducer must stay pure, and where progress side effects belong instead.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.