Static HTML and server rendering → Hooks
1991 – today · 2018 – today
What changed
- Where the state lives
Static HTML and server rendering
On the server: the todo list is server data; the current filter is in the URL and in hidden form fields.
Hooks
In
useState: the list lives in theuseTodos()hook, the filter and the text field in the component.- How the page is rendered
Static HTML and server rendering
The server writes the whole page as an HTML string for every request; the browser only displays it.
Hooks
React renders the whole
Appfrom state on every change and updates only the DOM that differs.- What happens on a change
Static HTML and server rendering
Every action is a request: a form POST or a link GET, answered by a complete new page.
Hooks
A handler calls a setter with a new array; React re-runs the component and recomputes
shownandleft.- How the code is organised
Static HTML and server rendering
One server program that routes requests and renders pages. No JavaScript is needed in the browser.
Hooks
A function component plus a custom hook: logic is grouped by feature and can be reused.
Why it changed
What hurt in each era along the way, and the era that came next.
Static HTML and server rendering→Dynamic HTML and the browser wars
Every change, even ticking one checkbox, is a round trip to the server and a new page: the screen flashes, the scroll position and anything half-typed are lost, and the user waits for the network each time. Pages could not react to the user on their own. JavaScript (1995) and Dynamic HTML let the page change itself in the browser.
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.
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 withattachEventinstead ofaddEventListener, 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.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.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.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 asetTimeoutcallback 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.
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,
setStatecalls 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.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/mapDispatchToPropsto 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.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.
SSR, SSG and meta-frameworks→Hooks
Pages now arrived rendered, but the components were still classes: one feature's logic was spread over
componentDidMount,componentDidUpdateandcomponentWillUnmount, sharing stateful logic needed higher-order components or render props, and every handler had to be bound tothis(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.
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.
Static HTML and server rendering
plain browser APIs, no library
/server.js · 83 lines
// Static HTML era: the server builds every page; the browser shows it and sends forms back.
// In the 1990s this was a CGI script (often Perl, later PHP); here it is JavaScript.
// The "database" lives on the server, so the list survives every page load.
const todos = [
{ id: 1, title: "Read the docs", done: true },
{ id: 2, title: "Write the app", done: false },
];
let nextId = 3;
const FILTERS = { all: "All", active: "Active", done: "Done" };
// Text typed by users must be escaped before it goes into the HTML.
function escapeHtml(text) {
return String(text)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
}
function renderPage(filter) {
const shown = todos.filter((t) => filter === "all" || (filter === "done") === t.done);
const left = todos.filter((t) => !t.done).length;
// Every todo gets its own little form: toggling it is a POST to the server.
const items = shown
.map(
(t) => `
<li${t.done ? ' class="done"' : ""}>
<form method="post" action="/todos/${t.id}/toggle">
<input type="hidden" name="filter" value="${filter}">
<button type="submit" data-toggle>${t.done ? "Undo" : "Done"}</button>
</form>
<span class="title">${escapeHtml(t.title)}</span>
</li>`,
)
.join("");
// Filters are plain links: choosing one loads a new page.
const links = Object.entries(FILTERS)
.map(
([name, label]) =>
`<a href="/?filter=${name}" data-filter="${name}"${name === filter ? ' class="selected"' : ""}>${label}</a>`,
)
.join(" ");
return `
<main class="todo-app">
<h1>Todos</h1>
<form id="todo-form" method="post" action="/todos">
<input type="hidden" name="filter" value="${filter}">
<input id="new-todo" name="title" placeholder="What needs doing?" autocomplete="off" aria-label="New todo">
<button id="add" type="submit">Add</button>
</form>
<ul id="todo-list">${items}
</ul>
<div class="footer">
<span id="todo-count">${left} left</span>
<div class="filters">${links}</div>
</div>
</main>`;
}
// One request in, one whole page out. The answer to a POST is the new page itself.
export function handle({ method, path, query, form }) {
const asked = form?.filter ?? query.filter;
const filter = Object.hasOwn(FILTERS, asked ?? "") ? asked : "all";
if (method === "POST" && path === "/todos") {
const title = (form.title ?? "").trim();
if (title) todos.push({ id: nextId++, title, done: false });
}
const toggle = path.match(/^\/todos\/(\d+)\/toggle$/);
if (method === "POST" && toggle) {
const todo = todos.find((t) => t.id === Number(toggle[1]));
if (todo) todo.done = !todo.done;
}
if (path === "/" || method === "POST") return { status: 200, body: renderPage(filter) };
return { status: 404, body: "<h1>Not found</h1>" };
}Hooks
React 19.3.0, React DOM 19.3.0
/src/App.jsx · 73 lines
// Hooks era: function components hold state with useState; the UI is computed from it.
import { useState } from "react";
import { useTodos } from "./useTodos.js";
const FILTERS = { all: "All", active: "Active", done: "Done" };
export default function App() {
const { todos, add, toggle } = useTodos();
const [filter, setFilter] = useState("all");
const [title, setTitle] = useState("");
// Derived values are computed on every render, not stored as state.
const shown = todos.filter((t) => filter === "all" || (filter === "done") === t.done);
const left = todos.filter((t) => !t.done).length;
function handleSubmit(event) {
event.preventDefault();
const text = title.trim();
if (!text) return;
add(text);
setTitle("");
}
return (
<main className="todo-app">
<h1>Todos</h1>
<form id="todo-form" onSubmit={handleSubmit}>
<input
id="new-todo"
value={title}
onChange={(event) => setTitle(event.target.value)}
placeholder="What needs doing?"
autoComplete="off"
aria-label="New todo"
/>
<button id="add" type="submit">
Add
</button>
</form>
<ul id="todo-list">
{shown.map((todo) => (
<li key={todo.id} className={todo.done ? "done" : undefined}>
<label>
<input
type="checkbox"
data-toggle
checked={todo.done}
onChange={() => toggle(todo.id)}
/>{" "}
<span className="title">{todo.title}</span>
</label>
</li>
))}
</ul>
<div className="footer">
<span id="todo-count">{left} left</span>
<div className="filters">
{Object.entries(FILTERS).map(([name, label]) => (
<button
key={name}
type="button"
data-filter={name}
className={filter === name ? "selected" : undefined}
onClick={() => setFilter(name)}
>
{label}
</button>
))}
</div>
</div>
</main>
);
}