UI as a function of state

Describe the screen for any state, then redraw. Simple, and broken.

Builds on The DOM and the sync problem.

The last chapter ended with a page that was quietly wrong: the data said one thing, the screen said another, because an event handler forgot to patch one piece of DOM. The fix it pointed at was to stop writing transitions and start describing states.

Here's the most direct way to do that. Write one function that takes your data and returns the whole screen. Whenever the data changes, call it again and redraw. It's about fifteen lines of code, it makes the sync bug impossible, and it's the idea React is built on. It also breaks in ways you can feel within seconds, and those breakages are exactly what the rest of Part 2 fixes.

The problem: patching by hand doesn't scale#

In chapter 1, every handler had two jobs: change the data, then find and fix each DOM node that depended on it. The number of places to fix grew with every feature, and forgetting one was silent.

What if handlers only had the first job? They change the data. Something else, one function that knows how the whole screen looks for any data, takes care of the screen. Handlers stop knowing about the DOM at all.

That's the whole idea in one line:

UI = view(state);

state is plain data. view is a function that turns it into a description of the screen. If the function is right for every state, the screen is right after every change, because nothing is patched: it's recomputed.

Build it: render(state) with innerHTML#

The simplest description of a screen the browser understands is a string of HTML, and the simplest way to put a string on screen is innerHTML. So:

  • state holds everything the screen depends on.
  • view(state) returns an HTML string for the whole screen.
  • render() assigns root.innerHTML = view(state).
  • setState(next) stores the new state and calls render().

Here's chapter 1's todo list, rewritten this way. Check and uncheck items, then press Clear done. Watch the counter.

The todo list as view(state)
let state = {
  todos: [
    { id: 1, text: "Buy milk", done: true },
    { id: 2, text: "Walk dog", done: false },
    { id: 3, text: "Read", done: false },
  ],
};

// The whole screen, as a function of state. No DOM calls in here.
function view(state) {
  const left = state.todos.filter((t) => !t.done).length;
  return `
    <h3>Todos</h3>
    <ul>
      ${state.todos
        .map(
          (t) => `<li style="text-decoration: ${t.done ? "line-through" : "none"}">
            <input type="checkbox" data-id="${t.id}" ${t.done ? "checked" : ""}> ${t.text}
          </li>`,
        )
        .join("")}
    </ul>
    <p>${left} left</p>
    <button data-action="clear">Clear done</button>
  `;
}

const root = document.getElementById("root");

function render() {
  root.innerHTML = view(state);
}

function setState(next) {
  state = { ...state, ...next };
  render();
}

// Handlers only change data. They never touch the DOM.
// One listener on the root survives every redraw (event delegation).
root.addEventListener("change", (event) => {
  const id = Number(event.target.dataset.id);
  setState({
    todos: state.todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)),
  });
});

root.addEventListener("click", (event) => {
  if (event.target.dataset.action === "clear") {
    setState({ todos: state.todos.filter((t) => !t.done) });
  }
});

render();

The counter is always right, and nobody wrote code to keep it right. The Clear done feature that took a dozen fiddly lines in chapter 1 is one line here: change the data. The <li> lookups by id, the "did I remember the counter" bookkeeping, all gone.

A few details in that code are worth noticing, because they come back later:

  • view is pure. It reads state and returns a string. It doesn't change anything, call the network or touch the DOM. Same state in, same screen out. React asks the same of your components, and for the same reason: it wants to call them whenever it needs to.
  • State is replaced, not mutated. setState builds a new object, and the toggle builds a new array with map. Nothing depends on that yet, but React will: it compares old and new values to decide what changed.
  • Listeners live on the root. Every redraw destroys the checkboxes and buttons, so listeners attached to them would vanish. One listener on root, which is never replaced, catches events as they bubble up and reads data-id to see what was clicked. React does the same thing: it attaches its listeners to the root container, not to each element.
The state to view loop
state{ todos, query }view(state)pure functionHTML string'<ul><li>…'DOMon screeninnerHTML
Step 1 of 6

State is plain data: one object holds everything the screen depends on. Nothing else is allowed to be the truth.

This is what people mean by declarative UI. You no longer describe how to get from one screen to the next. You describe what the screen is for a given state, and the transitions are somebody else's problem. Here, that somebody is a sledgehammer: throw everything away and rebuild.

Where it breaks#

Re-rendering everything isn't wrong. Recreating everything is. Three things go wrong, and you can see all three in under a minute.

Typing loses focus#

Here's a list with a filter box. Every keystroke updates state.query, which re-renders the list. Click the box and type "an".

A filter that fights you
let state = {
  query: "",
  fruits: ["Apple", "Banana", "Cherry", "Mango", "Orange", "Pear"],
};

function view(state) {
  const q = state.query.toLowerCase();
  const visible = state.fruits.filter((f) => f.toLowerCase().includes(q));
  return `
    <label>Filter <input id="filter" value="${state.query}"></label>
    <ul>${visible.map((f) => `<li>${f}</li>`).join("")}</ul>
    <p>${visible.length} of ${state.fruits.length}</p>
  `;
}

const root = document.getElementById("root");
function render() {
  root.innerHTML = view(state);
}
function setState(next) {
  state = { ...state, ...next };
  render();
}

root.addEventListener("input", (event) => {
  if (event.target.id === "filter") setState({ query: event.target.value });
});

render();

The first letter works. The second goes nowhere, because the input you were typing in no longer exists. innerHTML replaced it with a new <input> that has the right value but has never been focused. You have to click again for every character.

Focus isn't data you put in state. It belongs to the DOM node. So does the caret position, the text selection, and whether an IME (the input method used to type Japanese or Chinese) is halfway through composing a character. Recreate the node and all of it resets.

Anything the DOM remembers is wiped#

Focus is one example of a general rule from chapter 1: the DOM is stateful. Here's a screen that re-renders once a second for a perfectly reasonable reason, a clock in the header. Scroll the list down a bit, then start typing in the box. Wait a second.

A clock that resets everything
let state = {
  now: new Date(),
  todos: Array.from({ length: 20 }, (_, i) => `Todo number ${i + 1}`),
};

function view(state) {
  return `
    <p><strong>${state.now.toLocaleTimeString()}</strong></p>
    <input placeholder="New todo (try typing here)">
    <ul style="height: 110px; overflow: auto; border: 1px solid #ddd; margin-top: 8px">
      ${state.todos.map((t) => `<li>${t}</li>`).join("")}
    </ul>
  `;
}

const root = document.getElementById("root");
function render() {
  root.innerHTML = view(state);
}
function setState(next) {
  state = { ...state, ...next };
  render();
}

setInterval(() => setState({ now: new Date() }), 1000);
render();

Every tick, the scroll position snaps back to the top and the half-typed todo disappears. Nothing about the list or the input changed. They were destroyed anyway, because the only tool render has is "rebuild everything".

You could chase each case: put the input's text in state, save scrollTop before rendering and restore it after, save focus and the selection. People did, for years. You'll write that patch yourself in the exercise below, and it shows the problem: you're back to bookkeeping by hand, this time for DOM state instead of app state, and you'll forget one (a playing video, an open <details>, a CSS transition halfway through).

It's slow, and gets slower#

Rebuilding the DOM means parsing HTML, creating every node, recalculating styles and laying out the page again, even if one checkbox changed. Here are 3,000 rows. Toggle row 1 both ways and compare the timings in the console.

Redraw everything versus patch one node
<button id="all">Toggle row 1: redraw all</button>
<button id="one">Toggle row 1: patch one node</button>
<div id="root" style="height: 120px; overflow: auto"></div>
Nothing logged yet.

Exact numbers depend on your machine, but the shape doesn't: the full redraw costs milliseconds, the single patch costs a small fraction of one, and the gap grows with the size of the page. At 60 frames a second the browser has about 16 milliseconds per frame for everything, so a redraw-everything approach runs out of room as screens grow, especially if it runs on every keystroke.

What we actually want#

Keep the part that worked and drop the part that didn't:

  • Keep: writing the screen as view(state). Handlers change data, one function describes the result, and the sync bug can't happen.
  • Drop: throwing the old DOM away. The live DOM should be updated in place, touching only what differs between the old screen and the new one, so the input you're typing in survives.

To update in place, something has to compare "the screen last time" with "the screen this time" and work out the smallest set of DOM changes. You can't do that well with HTML strings: two strings tell you they differ, not which node changed or which node is which. You need the description of the screen as data, a tree of plain objects that's cheap to create, keep and compare.

That tree is what React calls elements, and comparing two of them is what it calls reconciliation. The next chapter builds the first piece: what JSX really is, and the objects it produces. By chapter 5 you'll have a toy render that diffs two trees and keeps that filter box focused.

Fix the focus bug by hand#

Fix itKeep the filter box focused

Change render so typing in the filter works: after each redraw, the filter input should still be focused, with the caret where it was. Don't change view. Press Check when you think it works.

let state = {
  query: "",
  fruits: ["Apple", "Banana", "Cherry", "Mango", "Orange", "Pear"],
};

function view(state) {
  const q = state.query.toLowerCase();
  const visible = state.fruits.filter((f) => f.toLowerCase().includes(q));
  return `
    <label>Filter <input id="filter" value="${state.query}"></label>
    <ul>${visible.map((f) => `<li>${f}</li>`).join("")}</ul>
  `;
}

const root = document.getElementById("root");

function render() {
  // TODO: remember which element had focus (and its caret) before the redraw,
  // then restore both on the new element after it.
  root.innerHTML = view(state);
}

function setState(next) {
  state = { ...state, ...next };
  render();
}

root.addEventListener("input", (event) => {
  if (event.target.id === "filter") setState({ query: event.target.value });
});

render();

Pitfalls#

Check your understanding#

PredictWhat survives a tick?

In the clock example, you type "milk" into the input, and you've scrolled the list to "Todo number 10". The clock ticks. Which of these survive: the text "milk", the scroll position, the current time on screen, the 20 todos?

Quick checkWhy focus is lost

Why does the filter input lose focus after the first keystroke?

Explain it out loudWhy not re-render everything?

An interviewer asks: "If UI is a function of state, why doesn't React just re-render everything into the DOM with innerHTML on every change?"

Interview angle

Say it in 30 seconds

Declarative UI means writing one function, view(state), that returns the whole screen for any state. Event handlers only change data, and the screen is recomputed, so it can't drift out of sync. The naive version rebuilds the DOM with innerHTML on every change, which breaks: DOM nodes hold their own state, like focus, the caret, scroll and half-typed text, and recreating them wipes it. It's also slow, because the browser parses and lays out everything again. React keeps the view(state) model but updates the DOM in place, touching only what changed.

What does "UI is a function of state" mean?

basic

Why not re-render the whole page with innerHTML whenever state changes?

basic

Why does it matter that the view function is pure?

intermediate

In a redraw-everything renderer, why attach event listeners to the root instead of each element?

intermediate

What would a renderer need in order to keep view(state) but stop losing DOM state?

senior

Recap#

  • Declarative UI means one function, view(state), describes the screen for any state. Handlers only change data.
  • Re-rendering from state makes the chapter 1 sync bug impossible: nothing is patched by hand, everything is recomputed.
  • Rebuilding the DOM with innerHTML throws away state that lives in DOM nodes: focus, caret, scroll, selection, half-typed text.
  • It also costs parsing, node creation and layout for the whole page on every change, and the cost grows with the page.
  • The fix is to keep view(state) but update the live DOM in place, touching only what changed. That needs the UI described as data, not strings: elements.

Sources#