State plus an action produces next state
A reducer is a pure function receiving current state and an action record, then returning the next state. An action says what happened, such as loading, loaded, failed, or toggle. It does not perform the request itself.
The switch statement compares one value with named cases. Each return exits the function, so there is no fall-through here. A default case rejects unknown actions: that helps catch a typo rather than quietly producing a misleading UI. Another system might deliberately ignore unknown actions; define your policy.
The reading queue's state contains status, results, saved, and error. Starting a search clears old results and errors but keeps saved books. A successful empty list is ready. Failure keeps saved books and supplies feedback. Cancelling returns to idle. These are product decisions, and tests should express them.
Do not store values you can reliably derive, such as savedCount, alongside saved unless there is a reason. Duplicated state creates more transitions that must stay synchronized. Keep HTTP, rendering, and storage outside the reducer so its tests need no browser.
Predict and trace
Write the output before running. Follow the values through each call; if your prediction differs, identify the first step that surprised you.
function reduce(state, action) {
switch (action.type) {
case "loading":
return { ...state, status: "loading", results: [], error: "" };
case "loaded":
return { ...state, status: "ready", results: action.books, error: "" };
default:
throw new Error("Unknown action");
}
}
const before = {
status: "idle",
results: [],
saved: [{ id: "js" }],
error: ""
};
const after = reduce(before, { type: "loaded", books: [] });
console.log(before.status);
console.log(after.status);
console.log(after.saved.length);Check your prediction
idle
ready
1The empty successful result changes status without erasing saved books or mutating the previous state.
Actions describe events; reducers apply rules
A reducer receives the previous state and an action, then computes the next state. It should not start a request, write storage or render a page inside that calculation. Keeping side effects outside makes a transition reproducible with the same arguments.
A transition should preserve unrelated state. Loading new results must not silently clear the saved list unless that is the stated policy. Test both the changed field and the fields that should survive; a correct status alone is insufficient.
function reduce(state, action) {
if (action.type === "save") {
return { ...state, saved: [...state.saved, action.book] };
}
return state;
}
const before = { query: "loops", saved: [] };
const after = reduce(before, { type: "save", book: { id: "a" } });
console.log(before.saved.length, after.saved.length);
console.log(after.query);Check your prediction
0 1
loopsThe new saved array and outer state preserve the old snapshot. Query is retained through the spread. None of this requires I/O in the reducer.
function reduce(state, action) {
return action.type === "reset" ? { count: 0 } : state;
}
const before = { count: 2 };
console.log(reduce(before, { type: "unknown" }) === before);
console.log(reduce(before, { type: "reset" }).count);Check your prediction
true
0This toy chooses to ignore unknown actions. The earlier full reducer chooses to throw; both require an explicit contract. Do not accidentally change the policy while refactoring a switch.
Try the rule on new inputs
For each real action, list changed and preserved fields. Test an unknown action according to the actual reducer contract. Keep async scheduling tests in the controller layer, where the side effects belong.
Debug a plausible mistake
Repair a mutating reducer
Produce the next count without changing the previous state. Print 0 then 1. Call the reducer twice with the same original state and explain why each result should still be 1.
Predict the supplied program's actual behavior first. It runs without an error, but breaks the requirement. Make a small repair, then try a case that would distinguish the repaired version from the original.
function increment(state) {
state.count += 1;
return state;
}
const original = { count: 0 };
const next = increment(original);
console.log(original.count);
console.log(next.count);Hint 1: the idea
Returning a reference does not prove the previous state was preserved.
Hint 2: a first step
Construct a new object with the updated count rather than assigning into state.
Show one solution
function increment(state) {
return { ...state, count: state.count + 1 };
}
const original = { count: 0 };
const next = increment(original);
console.log(original.count);
console.log(next.count);0
1The original printed 1 and 1: increment changed original.count in place and returned the same object, so "previous" and "next" were one state. Spreading into a new object leaves the input untouched. Calling increment(original) twice now gives 1 both times, because each call starts from the unchanged original rather than from a state the last call edited.
Build it yourself
A reading-queue reducer
Write reduceQueue(state, action) for a state { items, notice }. It handles two action types. { type: "add", book } appends the book, unless a book with that id is already queued, in which case items stay the same and the notice says so. { type: "remove", id } removes that book, or leaves items alone with the notice Nothing to remove. Any other type throws. Never change the state you were given. The loop applies five actions and then an unknown one, and should print:
js | Added Notes
js,web | Added The Web
js,web | Notes is already queued
web | Removed
web | Nothing to remove
Unknown action: clear
initial untouched: truefunction reduceQueue(state, action) {
// Handle "add" and "remove"; throw for anything else.
return state;
}
const initial = { items: [], notice: "" };
const actions = [
{ type: "add", book: { id: "js", title: "Notes" } },
{ type: "add", book: { id: "web", title: "The Web" } },
{ type: "add", book: { id: "js", title: "Notes" } },
{ type: "remove", id: "js" },
{ type: "remove", id: "css" }
];
let state = initial;
for (const action of actions) {
state = reduceQueue(state, action);
console.log(`${state.items.map(book => book.id).join(",") || "-"} | ${state.notice}`);
}
try {
reduceQueue(state, { type: "clear" });
} catch (error) {
console.log(error.message);
}
console.log(`initial untouched: ${initial.items.length === 0}`);Hint 1: the idea
Each action type is one case that returns a whole new state. The "nothing changes" outcomes still return a new object, because the notice changes, but they reuse the same items array.
Hint 2: a first step
Write the switch with only the "add" case (no duplicate check yet) and the default that throws. Run it: the third line shows js,web,js. That duplicate is what the check inside "add" must prevent.
Show one solution
function reduceQueue(state, action) {
switch (action.type) {
case "add":
if (state.items.some(book => book.id === action.book.id)) {
return { ...state, notice: `${action.book.title} is already queued` };
}
return { items: [...state.items, action.book], notice: `Added ${action.book.title}` };
case "remove":
if (!state.items.some(book => book.id === action.id)) {
return { ...state, notice: "Nothing to remove" };
}
return {
items: state.items.filter(book => book.id !== action.id),
notice: "Removed"
};
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
const initial = { items: [], notice: "" };
const actions = [
{ type: "add", book: { id: "js", title: "Notes" } },
{ type: "add", book: { id: "web", title: "The Web" } },
{ type: "add", book: { id: "js", title: "Notes" } },
{ type: "remove", id: "js" },
{ type: "remove", id: "css" }
];
let state = initial;
for (const action of actions) {
state = reduceQueue(state, action);
console.log(`${state.items.map(book => book.id).join(",") || "-"} | ${state.notice}`);
}
try {
reduceQueue(state, { type: "clear" });
} catch (error) {
console.log(error.message);
}
console.log(`initial untouched: ${initial.items.length === 0}`);js | Added Notes
js,web | Added The Web
js,web | Notes is already queued
web | Removed
web | Nothing to remove
Unknown action: clear
initial untouched: trueThe duplicate and missing-id branches spread state and replace only notice, so items is the very same array: nothing was copied that did not change. The successful branches build new arrays with spread and filter, which is why initial is still empty at the end. notice is part of the state, not something printed from inside the reducer, so a test or a renderer can read it. The default case turns a typo such as "clear" into an error naming the action instead of a silent no-op.
Explain before moving on
What is an action, and who performs the effect that leads to it? Why does loading preserve saved?
Completion is saved in this browser only. It does not measure mastery.