Skip to content
FrontDepth, Home

Dynamic HTML and the browser wars → Signals and fine-grained reactivity

1995 – today · 2021 – today

Older era
Newer era
Compare

What changed

Where the state lives

Dynamic HTML and the browser wars

In the page: a JavaScript array and a filter variable. Nothing is saved; a reload starts again from the code.

Signals and fine-grained reactivity

In signals: the list and the filter are signals, and each todo's done is a signal of its own. left and each row's shown are computed.

How the page is rendered

Dynamic HTML and the browser wars

render() builds the whole list as one HTML string and swaps it in with innerHTML.

Signals and fine-grained reactivity

Plain DOM: a row is built once, when its todo appears. After that only effects touch it; there is no virtual DOM and no template re-render.

What happens on a change

Dynamic HTML and the browser wars

Handler attributes (onsubmit, onclick) call global functions that change the array and call render().

Signals and fine-grained reactivity

Setting .value re-runs only the effects that read that signal, right away: ticking a todo updates its row's class and the counter text, nothing else.

How the code is organised

Dynamic HTML and the browser wars

One script of global functions, wired to the page by attributes in the HTML. No server is involved.

Signals and fine-grained reactivity

Signals and computed values at the top, then small effects, each bound to one piece of the DOM.

Why it changed

What hurt in each era along the way, and the era that came next.

  1. Dynamic HTML and the browser wars→AJAX

    The page could change itself, but it could not exchange data with the server without leaving: loading fresh data or saving a change still meant a form submission or a link and a whole new page, and everything kept in variables was gone after it. On top of that, every browser needed its own branch of the code. XMLHttpRequest and the AJAX approach let a script talk to the server in the background and update only the part of the page that changed.

  2. AJAX→jQuery

    Every browser did it a little differently. Internet Explorer 5 and 6 created the object with new ActiveXObject("Microsoft.XMLHTTP"), Internet Explorer before version 9 attached events with attachEvent instead of addEventListener, and each browser had its own DOM quirks, so scripts grew long and full of browser checks. Libraries like jQuery wrapped XHR, events and the DOM in one short API that worked the same in every browser.

  3. jQuery→MVC in the browser (Backbone)

    When the data lives only in the DOM, every feature reads and writes the page directly: the counter counts <li> elements, the filter checks classes. As apps grew, handlers changing the page from many places became hard to follow ("jQuery spaghetti"), and there was no model of the data to test, save or reuse. Libraries like Backbone moved the data into models and kept the page in views.

  4. MVC in the browser (Backbone)→Two-way binding (AngularJS)

    Backbone left the wiring to you. Every view subscribed to its models by hand, chose what to redraw and read form fields back itself, so much of the code only connected data to the DOM. A view thrown away without remove() stayed subscribed and kept reacting as a "zombie view", and re-rendering a template replaced elements, losing focus and half-typed text. AngularJS answered with two-way data binding: the HTML declares what shows what, and the framework keeps the page and the data in sync.

  5. Two-way binding (AngularJS)→React and the virtual DOM

    Every binding added a watcher, and every digest checked all of them, at least twice whenever something had changed, so pages with many bindings slowed down on each click or keystroke (1.3 added one-time bindings, ::, to cut the count). Two-way bindings and watchers that change other values made it hard to see what changed what, and code outside AngularJS, like a setTimeout callback or a jQuery plugin, had to remember to call $scope.$apply().

    Angular 2 was a new framework rather than the next version: an app could not just upgrade, and the official path was to migrate it piece by piece, with both frameworks running side by side. React answered with one-way data flow: a component renders from its state, and a virtual DOM works out what to change on the page.

  6. React and the virtual DOM→Flux and Redux

    State that several components need has to live in their closest common parent and travel down as props through every component in between, even those that only pass it on, while callbacks travel down the same way to change it. In a large app, setState calls in many components, triggered by clicks, server responses and timers, all changed what the screen showed, so it was hard to follow why it looked the way it did. Flux and Redux moved the shared state out of the components into a store that changes only through actions.

  7. Flux and Redux→Component frameworks (Vue, Angular, Svelte)

    Every small feature needed the same pieces in several files: an action type constant, an action creator, a case in a reducer, and mapStateToProps / mapDispatchToProps to connect a component, plus objects copied by hand so that nothing was mutated. Setting up a store with middleware and the DevTools took more code still. Redux itself later answered with Redux Toolkit; component frameworks like Vue, Angular and Svelte offered reactive state you change directly and HTML templates that update themselves, with much less ceremony.

  8. Component frameworks (Vue, Angular, Svelte)→SSR, SSG and meta-frameworks

    These apps still rendered in the browser. The server sent an almost empty page, and nothing useful appeared until the framework and the app's JavaScript had downloaded and run; crawlers and link previews that do not run JavaScript saw nothing. Routing, server rendering, code splitting and data loading were left to each team to put together. Meta-frameworks such as Next.js and Nuxt bundled those pieces around the component framework and rendered pages on the server or at build time.

  9. SSR, SSG and meta-frameworks→Hooks

    Pages now arrived rendered, but the components were still classes: one feature's logic was spread over componentDidMount, componentDidUpdate and componentWillUnmount, sharing stateful logic needed higher-order components or render props, and every handler had to be bound to this (see the constructor). Hooks (React 16.8, 2019) gave function components state and effects that can be shared as custom hooks.

    Hydration had its own cost: the browser downloads and runs the code of the whole page, even of parts that never change, and the data travels twice, as HTML and as JSON. Islands and server components later went after that.

  10. Hooks→Server components and islands

    Everything still ran in the browser: the page arrived empty, every component's JavaScript had to download, run and render before anything useful appeared, and server rendering hydrated the whole page even where nothing was interactive. Effects with dependency arrays and stale closures became a common source of bugs. Islands and React Server Components moved the non-interactive parts back to the server.

  11. Server components and islands→Signals and fine-grained reactivity

    Inside an island, and inside every client component, nothing changed: each state change runs the component again and React compares the new output with the old. Ticking one checkbox here re-renders the whole TodoApp and compares every item; keeping large islands fast takes memo, useMemo and useCallback. Signals and fine-grained reactivity track which piece of the DOM reads which value and update only that.

The same app, side by side

The main file of each version. Both apps pass the same test: same markup, same behaviour, different ideas.

The apps run in sandboxes in your browser.

Dynamic HTML and the browser wars
Signals and fine-grained reactivity

Dynamic HTML and the browser wars

plain browser APIs, no library

/src/main.js · 73 lines

JavaScript
// DHTML era: the page changes itself in the browser. The list is a JavaScript array, and
// render() writes it into the page as one HTML string. No server is asked.

// The state is plain variables in the page: a reload starts again from these lines.
var todos = [
  { id: 1, title: "Read the docs", done: true },
  { id: 2, title: "Write the app", done: false }
];
var nextId = 3;
var filter = "all";
var FILTERS = ["all", "active", "done"];

// The text the user typed becomes part of the HTML, so it is escaped first.
function escapeHtml(text) {
  return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}

function render() {
  var html = "";
  var left = 0;
  var i, todo;
  for (i = 0; i < todos.length; i++) {
    todo = todos[i];
    if (!todo.done) left++;
    if (filter == "all" || (filter == "done") == todo.done) {
      // The handler is part of the string: onclick calls a global function with the id.
      html += '<li' + (todo.done ? ' class="done"' : '') + '><label>' +
        '<input type="checkbox" data-toggle onclick="toggleTodo(' + todo.id + ')"' +
        (todo.done ? ' checked' : '') + '> ' +
        '<span class="title">' + escapeHtml(todo.title) + '</span></label></li>';
    }
  }
  // innerHTML throws the old items away and builds new ones, so a focused checkbox loses focus.
  document.getElementById("todo-list").innerHTML = html;
  document.getElementById("todo-count").innerHTML = left + " left";
  for (i = 0; i < FILTERS.length; i++) {
    document.getElementById("filter-" + FILTERS[i]).className = FILTERS[i] == filter ? "selected" : "";
  }
}

function addTodo() {
  var field = document.getElementById("new-todo");
  var title = field.value.replace(/^\s+|\s+$/g, "");
  if (title != "") {
    todos.push({ id: nextId++, title: title, done: false });
    field.value = "";
    render();
  }
  // false cancels what the browser would do next: send the form and load a new page.
  return false;
}

function toggleTodo(id) {
  for (var i = 0; i < todos.length; i++) {
    if (todos[i].id == id) todos[i].done = !todos[i].done;
  }
  render();
}

function setFilter(name) {
  filter = name;
  render();
}

// A <script> of the time ran in the global scope: every function above became global, and
// the onclick attributes could call it. The lab runs each file as a module with its own
// scope, so the functions the markup calls are put on window by hand.
window.addTodo = addTodo;
window.toggleTodo = toggleTodo;
window.setFilter = setFilter;

// Like a <script> at the end of <body>, this runs when the elements already exist: draw the list.
render();

Signals and fine-grained reactivity

Preact Signals 1.14.5

/src/main.js · 78 lines

JavaScript
// Signals era: state lives in signals, and each effect keeps one piece of the DOM in sync.
// An effect remembers which signals it read and re-runs only when one of them changes.
import { signal, computed, effect } from "@preact/signals-core";

let nextId = 1;
// Each todo's done is a signal of its own, so ticking one todo touches only its own row.
const createTodo = (title, done = false) => ({ id: nextId++, title, done: signal(done) });

const todos = signal([createTodo("Read the docs", true), createTodo("Write the app")]);
const filter = signal("all");
// A computed is cached: it is recomputed only after a signal it read has changed.
const left = computed(() => todos.value.filter((t) => !t.done.value).length);

const list = document.getElementById("todo-list");
const rowTemplate = document.getElementById("todo-row");

// Builds a row once. From then on only its own two effects touch it.
function renderRow(todo) {
  const li = rowTemplate.content.firstElementChild.cloneNode(true);
  const checkbox = li.querySelector("[data-toggle]");
  li.querySelector(".title").textContent = todo.title;
  checkbox.addEventListener("change", () => {
    todo.done.value = checkbox.checked;
  });

  // Re-runs only when THIS todo's done changes.
  effect(() => {
    li.classList.toggle("done", todo.done.value);
    checkbox.checked = todo.done.value;
  });

  // Recomputed when the filter or this todo's done changes. If the answer stays the same
  // (ticking a todo under "All"), the effect that reads it does not run at all.
  const shown = computed(() => filter.value === "all" || (filter.value === "done") === todo.done.value);
  effect(() => {
    li.style.display = shown.value ? "" : "none";
  });
  return li;
}

// Re-runs only when the list itself changes (a todo is added). It builds rows for new todos
// and leaves the existing ones alone. Nothing is ever removed here, so no effect is disposed.
const rendered = new Set();
effect(() => {
  for (const todo of todos.value) {
    if (rendered.has(todo)) continue;
    rendered.add(todo);
    list.append(renderRow(todo));
  }
});

// Re-runs when left changes: after adding or ticking a todo, never after picking a filter.
const count = document.getElementById("todo-count");
effect(() => {
  count.textContent = `${left.value} left`;
});

// Re-runs when the filter changes: moves the "selected" class.
const buttons = document.querySelectorAll("[data-filter]");
effect(() => {
  for (const button of buttons) button.classList.toggle("selected", button.dataset.filter === filter.value);
});

for (const button of buttons) {
  button.addEventListener("click", () => {
    filter.value = button.dataset.filter;
  });
}

document.getElementById("todo-form").addEventListener("submit", (event) => {
  event.preventDefault();
  const input = document.getElementById("new-todo");
  const title = input.value.trim();
  if (!title) return;
  // A new array, so the signal gets a new value and the effects that read it re-run.
  todos.value = [...todos.value, createTodo(title)];
  input.value = "";
});