JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 15: Interactive Application ArchitectureLesson 73 of 150About 50 minutes

Lesson 73: State-driven rendering

01Opening question

Several components show the same data. When it changes, how does each one find out?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Two views subscribe to one store. One dispatched action updates the state, and both views re-render from it.

const store = createStore({ count: 0 });
function createStore(state) {
  const subs = new Set();
  return {
    get: () => state,
    dispatch(action) {
      if (action.type === "inc") state = { ...state, count: state.count + 1 };
      subs.forEach((f) => f(state));
    },
    subscribe: (f) => { subs.add(f); f(state); }
  };
}
store.subscribe((s) => { document.querySelector("#a").textContent = s.count; });
store.subscribe((s) => { document.querySelector("#b").textContent = s.count > 0 ? "busy" : "idle"; });
store.dispatch({ type: "inc" });
console.log(document.querySelector("#a").textContent, document.querySelector("#b").textContent);

03Objective and prerequisites

Learning objective: Connect components to one store so every state change re-renders the views that depend on it, and keep updates predictable with actions.

You need: Lesson 72: Reusable UI components, Lesson 66: Understanding application state

Skills practised: Browser application architecture, State-driven rendering.

04Explanation

In state-driven rendering, the interface is always calculated from state. You never edit the page directly in response to a click; you change the state.

A store holds the state. Views subscribe to it and re-render whenever it changes.

Changes are described as actions: small objects such as { type: "add", text: "Milk" }. One function, the reducer, turns the old state and an action into the new state.

Because every change goes through one place, you can log every action and see exactly how the app got into its current state.

05Definitions

State-driven rendering
Rendering the interface entirely from state, and changing the interface only by changing state.
Action
An object describing a change, usually with a type and data.
Reducer
A pure function that takes the current state and an action and returns the new state.
Dispatch
Sending an action to the store so the reducer can apply it.
Subscriber
A function the store calls after each change, typically a view's render.

Open the full glossary

06Visual learning object

Dynamic list rendering laboratory. Dispatch actions to a list app and watch the reducer produce new state and the list re-render, with an action log you can replay.

Loading the interactive object…

Open the full Dynamic list rendering laboratory page with its guided experiment.

07Examples

ex-073-01A reducer Browser page (sandboxed preview)

All changes to a to-do list in one pure function.

function todos(state, action) {
  switch (action.type) {
    case "add":
      return [...state, { id: state.length + 1, text: action.text, done: false }];
    case "toggle":
      return state.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t));
    case "clearDone":
      return state.filter((t) => !t.done);
    default:
      return state;
  }
}
let s = [];
for (const a of [{ type: "add", text: "Read" }, { type: "add", text: "Run" }, { type: "toggle", id: 1 }, { type: "clearDone" }]) {
  s = todos(s, a);
  console.log(a.type, JSON.stringify(s.map((t) => t.text + (t.done ? "*" : ""))));
}
Sample input
None
Expected output
add ["Read"] add ["Read","Run"] toggle ["Read*","Run"] clearDone ["Run"]
Common mistake
Mutating state inside the reducer (state.push), which breaks change detection and replay.
Try this
Add an "edit" action that changes a todo's text.
Source
examples/ex-073-01-reducer.js

ex-073-02Several views, one store Browser page (sandboxed preview)

A list and a counter both re-render from the same state.

function createStore(reducer, state) {
  const subs = new Set();
  return {
    get: () => state,
    dispatch(action) { state = reducer(state, action); subs.forEach((f) => f(state)); },
    subscribe(f) { subs.add(f); f(state); return () => subs.delete(f); }
  };
}
const reducer = (s, a) => (a.type === "add" ? { items: [...s.items, "Item " + (s.items.length + 1)] } : s);
const store = createStore(reducer, { items: [] });
store.subscribe((s) => document.querySelector("#list").replaceChildren(...s.items.map((t) => Object.assign(document.createElement("li"), { textContent: t }))));
store.subscribe((s) => { document.querySelector("#count").textContent = s.items.length + " items"; });
document.querySelector("#add").addEventListener("click", () => store.dispatch({ type: "add" }));
document.querySelector("#add").click();
document.querySelector("#add").click();
console.log(document.querySelector("#list").children.length, document.querySelector("#count").textContent);
Sample input
None
Expected output
2 2 items
Common mistake
Updating the count in the click handler and forgetting it in another place that adds items.
Try this
Add a Remove last button.
Source
examples/ex-073-02-connected-views.js

ex-073-03Side effects in subscribers Browser page (sandboxed preview)

Saving belongs next to the store, not inside the reducer.

const reducer = (s, a) => (a.type === "setTheme" ? { ...s, theme: a.theme } : s);
let state = { theme: localStorage.getItem("theme") ?? "light" };
const subs = [
  (s) => { document.querySelector("#theme").textContent = "Theme: " + s.theme; },
  (s) => localStorage.setItem("theme", s.theme)
];
const dispatch = (a) => { state = reducer(state, a); subs.forEach((f) => f(state)); };
dispatch({ type: "setTheme", theme: "dark" });
console.log(document.querySelector("#theme").textContent, localStorage.getItem("theme"));
Sample input
None
Expected output
Theme: dark dark
Common mistake
Calling localStorage.setItem inside the reducer, so tests of the reducer write to storage.
Try this
Only save when the theme actually changed.
Source
examples/ex-073-03-effects.js

ex-073-04Logging and replaying actions Browser page (sandboxed preview)

A log of actions can rebuild any state.

const reducer = (n, a) => (a.type === "add" ? n + a.by : a.type === "reset" ? 0 : n);
const log = [];
let state = 0;
function dispatch(action) {
  log.push(action);
  state = reducer(state, action);
}
dispatch({ type: "add", by: 5 });
dispatch({ type: "add", by: 2 });
dispatch({ type: "reset" });
dispatch({ type: "add", by: 4 });
console.log("state:", state, "actions:", log.length);
const replayed = log.slice(0, 2).reduce(reducer, 0);
console.log("after 2 actions:", replayed);
Sample input
None
Expected output
state: 4 actions: 4 after 2 actions: 7
Common mistake
Changing state outside dispatch, which makes the log incomplete.
Try this
Add an undo that replays all but the last action.
Source
examples/ex-073-04-action-log.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

The reducer changes the old state

Return new state instead of mutating.

function cart(state, action) {
  if (action.type === "add") {
    state.push(action.item);
    return state;
  }
  return state;
}
const before = ["tea"];
const after = cart(before, { type: "add", item: "mug" });
console.log(before.length, after.length, before === after);

A counter reducer

Write a reducer with several actions.

function counter(state, action) {
  // TODO: "inc" adds action.by (default 1), "dec" subtracts 1 but never
  // below 0, "reset" returns 0; anything else returns state
}
const actions = [{ type: "inc" }, { type: "inc", by: 5 }, { type: "dec" }, { type: "dec" }, { type: "reset" }, { type: "dec" }];
let n = 0;
const seen = [];
for (const a of actions) { n = counter(n, a); seen.push(n); }
console.log(seen.join(" "));

A store-driven shopping list

Wire a reducer, a store and two views.

// reducer(state, action): "add" appends action.text (trimmed, ignored if empty),
//   "remove" deletes by index. State shape: { items: [] }
// createStore(reducer, initial) with get, dispatch, subscribe
// Views: #list (li per item) and #summary ("N items")
// The form dispatches "add". Add "Milk", "  ", "Eggs", then dispatch
// { type: "remove", index: 0 } and log the list text and summary.

09Prediction

Commit to an answer first, then run the real code to compare.

const reducer = (s, a) => (a.type === "add" ? s + 1 : s);
const actions = [{ type: "add" }, { type: "noop" }, { type: "add" }];
console.log(actions.reduce(reducer, 10));

What is printed?

10Debugging investigation

The list never shows new items

Dispatching add changes the state, but the list keeps showing only the first item. The view skips rendering when the items array has not changed.

function reducer(state, action) {
  if (action.type === "add") {
    state.items.push(action.text);
    return { ...state };
  }
  return state;
}
let state = { items: ["Tea"] };
let lastItems = null;
function view(s) {
  if (s.items === lastItems) return;
  lastItems = s.items;
  document.getElementById("list").replaceChildren(...s.items.map((t) => Object.assign(document.createElement("li"), { textContent: t })));
}
view(state);
state = reducer(state, { type: "add", text: "Mug" });
view(state);
console.log("rendered: " + document.getElementById("list").children.length);

More cases in the Debugging Detective Laboratory

11Practical scenario

Undo in editors

Drawing and spreadsheet apps keep every change as an action. Undo replays all actions except the last one through the reducer, and collaborative editors send the same actions to other people's browsers to keep everyone in sync.

const reducer = (s, a) => s + a;
const actions = [3, 4, -2];
console.log("now:", actions.reduce(reducer, 0), "after undo:", actions.slice(0, -1).reduce(reducer, 0));

12Knowledge check

1. What is a reducer?

  • A function that shrinks arrays
  • A pure function (state, action) => new state
  • A DOM method
  • A storage API

2. Where should saving to localStorage happen?

  • Inside the reducer
  • In a subscriber or around dispatch
  • In the action object
  • In CSS

3. Why does the view not update after dispatch?

case "add": state.items.push(action.item); return state;
  • The reducer mutated and returned the same object, and the view skips unchanged state
  • dispatch is async
  • Arrays cannot be state
  • Views cannot subscribe

4. Two views subscribe; one action is dispatched. How many times does each view render, counting the initial render on subscribe?

  • Once
  • Twice
  • Three times
  • Never

5. What does an action usually contain?

  • DOM elements
  • A type and the data needed for the change
  • The whole new state
  • A function

6. A counter appears in the header and the sidebar. Which is more reliable?

  • Each click handler updates both elements
  • Both views subscribe to one store and render from state
  • The sidebar copies the header's text
  • A timer syncs them

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • The reducer changes the old state: Prints 1 2 false; Unknown actions return the same state
  • A counter reducer: Prints the sequence; Unknown action
  • A store-driven shopping list: Prints Eggs 1 items; Reducer is pure; Store state matches

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-15-interactive-application-architecture/lesson-073-state-driven-rendering/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • The UI is a function of state; change state, not the page.
  • Actions describe changes; a pure reducer applies them.
  • Views subscribe to a store and re-render.
  • Side effects run outside the reducer.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation state-driven rendering
Context: I am learning state-driven rendering in JavaScript.
Task: Explain stores, actions, reducers and subscribers with a small list app.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction state-driven rendering drill
Context: I have practised state-driven rendering.
Task: Give me six reducers and action lists and ask what the final state is.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging state-driven rendering bug
Context: My view does not update after I dispatch an action.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation state-driven rendering practice
Context: I finished the state-driven rendering exercises.
Task: Create three exercises with reducers and connected views.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review state-driven rendering review
Context: Here is my code that uses state-driven rendering.
Task: Review my store and reducer for mutation and side effects.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.