Show contents
Chapter 1 of 6 · 20 min
State and rendering
By the end of this chapter, you'll be able to
- Centralise an application's state in a single store
- Describe each change with an action handled by a pure reducer
- Update the state without mutating it, using copies
- Wire the page's rendering to state changes
A store, actions, a reducer
Three pieces are enough:
- the state: an object that holds all the displayed data;
- actions: objects that describe what happened (
{ type: "add", title: "…" }); - the reducer: a pure function
(state, action) → new state. Pure means: same input, same output, and no change to what it's given.
The store keeps the state, applies actions with the reducer, and notifies its subscribers on every change. It's the model popularised by Redux, which you'll find under other names in most interface libraries.
function createStore(reducer, initialState) {
let state = initialState;
const subscribers = new Set();
return {
read: () => state,
dispatch(action) {
const before = state;
state = reducer(state, action);
if (state !== before) for (const subscriber of subscribers) subscriber(state);
},
subscribe(subscriber) {
subscribers.add(subscriber);
return () => subscribers.delete(subscriber);
},
};
}
function tasks(state, action) {
switch (action.type) {
case "add":
return { ...state, list: [...state.list, { id: state.nextId, title: action.title, done: false }], nextId: state.nextId + 1 };
case "toggle":
return { ...state, list: state.list.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t)) };
case "remove":
return { ...state, list: state.list.filter((t) => t.id !== action.id) };
default:
return state;
}
}
const show = (state) => state.list.map((t) => `${t.done ? "[x]" : "[ ]"} ${t.title}`).join(" | ") || "(empty)";
const store = createStore(tasks, { list: [], nextId: 1 });
store.subscribe((state) => console.log("render:", show(state)));
store.dispatch({ type: "add", title: "Fix the pump" });
store.dispatch({ type: "add", title: "Order the seeds" });
store.dispatch({ type: "toggle", id: 1 });
store.dispatch({ type: "unknown" });
store.dispatch({ type: "remove", id: 2 });
render: [ ] Fix the pump
render: [ ] Fix the pump | [ ] Order the seeds
render: [x] Fix the pump | [ ] Order the seeds
render: [x] Fix the pump
{ ...state, list: … }creates a new object that copies every property ofstateexceptlist, which is replaced.[...state.list, newItem]creates a new array. The old state is never changed.mapandfilteralso return new arrays: they're a reducer's natural tools.- The unknown action returns the state as is: the store sees that nothing changed (
state === before) and triggers no render.
The whole display (list, counter, filters) is recomputed from the state: impossible to forget a piece.
Text description of the animation
- The user ticks a task.
- The click handler doesn't touch the page: it dispatches an action describing what happened.
- The reducer computes a new state from the old one, without changing it.
- The store keeps the new state and calls its subscribers.
- The whole display (list, counter, filters) is recomputed from the state: impossible to forget a piece.
In a page, the subscriber recomputes the DOM. Rebuilding the whole list on every change is simple and fast enough for a few hundred items; libraries such as React or Vue only change the parts that differ, but the principle is the same:
const list = document.querySelector("#tasks");
store.subscribe((state) => {
list.replaceChildren(...state.list.map((t) => {
const li = document.createElement("li");
li.textContent = t.title;
li.classList.toggle("done", t.done);
li.addEventListener("click", () => store.dispatch({ type: "toggle", id: t.id }));
return li;
}));
});
Your turn
Mini-lab: a donation counter driven by the stateHTML · CSS · JS
Preview
Console
(Nothing in the console yet.)Your code runs in an isolated page, with no access to this site or the Internet · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Solved exercise: undoing the last action
Write a function withUndo(reducer) that returns a new reducer. Its state has the shape { past, present }: present is the normal state, past the list of previous states (20 at most). The { type: "undo" } action goes back to the previous state; an action that changes nothing must not fill the history. Test it with a simple counter.
Hint 1
reducer(state.present, action). If the result is identical to state.present, return state as is.Hint 2
present is state.past.at(-1), and the new past is state.past.slice(0, -1).Show the solution and common mistakes
function withUndo(reducer) {
return (state, action) => {
if (action.type === "undo") {
if (state.past.length === 0) return state;
return { past: state.past.slice(0, -1), present: state.past.at(-1) };
}
const next = reducer(state.present, action);
if (next === state.present) return state;
return { past: [...state.past, state.present].slice(-20), present: next };
};
}
const counter = (n, action) => (action.type === "plus" ? n + action.step : n);
const reducer = withUndo(counter);
let state = { past: [], present: 0 };
for (const action of [{ type: "plus", step: 5 }, { type: "plus", step: 3 }, { type: "noop" }, { type: "undo" }, { type: "plus", step: 10 }, { type: "undo" }, { type: "undo" }, { type: "undo" }]) {
state = reducer(state, action);
console.log(action.type.padEnd(4), "→", state.present, `(history: ${state.past.length})`);
}
plus → 5 (history: 1)
plus → 8 (history: 2)
noop → 8 (history: 2)
undo → 5 (history: 1)
plus → 15 (history: 2)
undo → 5 (history: 1)
undo → 0 (history: 0)
undo → 0 (history: 0)
Undoing costs almost nothing because states are never changed: each old state remains intact in the history. With a reducer that mutated the state in place, every item of past would point to the same object, and undo would be impossible.
Common mistakes:
- Recording actions that change nothing in the history: you'd then have to press "Undo" several times to see any effect.
- Forgetting the limit of 20: in an application left open all day, the history grows endlessly and ends up using a lot of memory.
Summary
- 1The interface is a function of the state: you change the state, and the display is recomputed.
- 2An action describes what happened; a pure reducer computes the new state.
- 3The state is never mutated: it's replaced by a copy (spread, map, filter).
- 4The store notifies its subscribers only when the state has really changed.
- 5Never-mutated states make undo and debugging very simple.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.