React and the virtual DOM → Server components and islands
2013 – today · 2020 – today
What changed
- Where the state lives
React and the virtual DOM
In
this.stateof the topAppclass: the todos, the filter and the typed text, changed only throughthis.setState.Server components and islands
In the island's
useState, started from the props the server serialized next to it. The static parts have no state at all.- How the page is rendered
React and the virtual DOM
render()returns the whole UI as React elements on every change; React compares them with the previous ones and patches only the DOM that differs.Server components and islands
The server renders the whole page to HTML; only the island's element is hydrated with
hydrateRoot(). React never touches the static HTML.- What happens on a change
React and the virtual DOM
A bound handler calls
this.setState; React merges the change into the state and callsrender()again.Server components and islands
Inside the island a setter re-renders
TodoAppand React updates the DOM that differs; the rest of the page never changes.- How the code is organised
React and the virtual DOM
A class component that owns the state and a small function component that gets props: data goes down as props, changes come back up through callbacks.
Server components and islands
Server-only components that never reach the browser, around client islands that each have their own root, script and props.
Why it changed
What hurt in each era along the way, and the era that came next.
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.
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.
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.
React and the virtual DOM
React 19.3.0, React DOM 19.3.0
/src/App.jsx · 98 lines
// Virtual DOM era: render() describes the whole UI from this.state, and React updates the DOM.
// JSX then compiled to React.createElement, so every file imported React; the automatic runtime used here does not need it.
import React from "react";
import TodoItem from "./TodoItem.jsx";
const FILTERS = { all: "All", active: "Active", done: "Done" };
let nextId = 3;
export default class App extends React.Component {
constructor(props) {
super(props);
// The top component owns the state; its children get pieces of it as props.
this.state = {
todos: [
{ id: 1, title: "Read the docs", done: true },
{ id: 2, title: "Write the app", done: false },
],
filter: "all",
title: "",
};
// A class method passed as a callback loses `this`, so each handler is bound once here.
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.toggle = this.toggle.bind(this);
}
handleChange(event) {
// setState merges the given keys into this.state and asks React to render again.
this.setState({ title: event.target.value });
}
handleSubmit(event) {
event.preventDefault();
const title = this.state.title.trim();
if (!title) return;
const todo = { id: nextId++, title, done: false };
// setState is a request, not an immediate change: the function form gets the latest state.
this.setState((state) => ({ todos: state.todos.concat(todo), title: "" }));
}
toggle(id) {
// Copy the todo instead of changing it. Object spread ({ ...t }) only became standard
// in ES2018, so code of the time used Object.assign.
this.setState((state) => ({
todos: state.todos.map((t) => (t.id === id ? Object.assign({}, t, { done: !t.done }) : t)),
}));
}
// React calls it again on every state change, compares the new elements with the previous ones
// (the virtual DOM) and changes only the DOM nodes that differ.
render() {
const { todos, filter, title } = this.state;
const shown = todos.filter((t) => filter === "all" || (filter === "done") === t.done);
const left = todos.filter((t) => !t.done).length;
return (
<main className="todo-app">
<h1>Todos</h1>
<form id="todo-form" onSubmit={this.handleSubmit}>
<input
id="new-todo"
value={title}
onChange={this.handleChange}
placeholder="What needs doing?"
autoComplete="off"
aria-label="New todo"
/>
<button id="add" type="submit">
Add
</button>
</form>
<ul id="todo-list">
{/* Data goes down as props; the change comes back up through onToggle. */}
{shown.map((todo) => (
<TodoItem key={todo.id} todo={todo} onToggle={this.toggle} />
))}
</ul>
<div className="footer">
<span id="todo-count">{left} left</span>
<div className="filters">
{Object.keys(FILTERS).map((name) => (
<button
key={name}
type="button"
data-filter={name}
className={filter === name ? "selected" : undefined}
onClick={() => this.setState({ filter: name })}
>
{FILTERS[name]}
</button>
))}
</div>
</div>
</main>
);
}
}Server components and islands
React 19.3.0, React DOM 19.3.0
/server.jsx · 48 lines
// Islands era: the server renders the whole page to HTML, and only the islands get JavaScript.
// An islands framework such as Astro does this for you: you only mark what is interactive.
import { renderToStaticMarkup, renderToString } from "react-dom/server";
import TodoApp from "./islands/TodoApp.jsx";
// The "database" lives on the server.
const todos = [
{ id: 1, title: "Read the docs", done: true },
{ id: 2, title: "Write the app", done: false },
];
// A server-only component: it runs here and leaves plain HTML behind. It ships NO JavaScript:
// this file is never sent to the browser, and nothing hydrates its HTML.
function Intro() {
return (
<>
<h1>Todos</h1>
<p>This heading and note are plain HTML with no JavaScript. Everything below them is an island.</p>
</>
);
}
// "<" is escaped so that a todo titled "</script>" cannot end the script element early.
function serialize(props) {
return JSON.stringify(props).replace(/</g, "\\u003c");
}
export async function handle({ method, path }) {
if (method !== "GET" || path !== "/") return { status: 404, body: "<h1>Not found</h1>" };
const props = { initialTodos: todos };
// Static part: HTML only, without the markers hydration needs. No JavaScript.
const intro = renderToStaticMarkup(<Intro />);
// The island: HTML that hydrateRoot can attach to, with its props as JSON right next to it.
const island = renderToString(<TodoApp {...props} />);
return {
status: 200,
body: `
<main class="todo-app">
${intro}
<div id="todo-island">${island}</div>
<script id="todo-island-props" type="application/json">${serialize(props)}</script>
</main>
<script src="/client.jsx"></script>`,
};
}