Skip to content
FrontDepth, Home

SSR, SSG and meta-frameworks → Hooks

2016 – today · 2018 – today

Older era
Newer era
Compare

What changed

Where the state lives

SSR, SSG and meta-frameworks

In the page component's this.state, started from the props the server loaded with getInitialProps(); a copy of those props travels with the HTML as JSON.

Hooks

In useState: the list lives in the useTodos() hook, the filter and the text field in the component.

How the page is rendered

SSR, SSG and meta-frameworks

The server renders the whole page to HTML with renderToString(); the browser hydrates it with hydrateRoot() and renders every later change itself.

Hooks

React renders the whole App from state on every change and updates only the DOM that differs.

What happens on a change

SSR, SSG and meta-frameworks

After hydration everything happens in the browser: a handler calls this.setState() and React re-renders the page component. Nothing goes back to the server.

Hooks

A handler calls a setter with a new array; React re-runs the component and recomputes shown and left.

How the code is organised

SSR, SSG and meta-frameworks

A page in pages/ written once for both sides, plus framework code: a server that renders and serializes, and a client entry that hydrates.

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.

  1. 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.

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.

SSR, SSG and meta-frameworks
Hooks

SSR, SSG and meta-frameworks

React 19.3.0, React DOM 19.3.0

/pages/index.jsx · 101 lines

JSX
// A page as Next.js apps wrote it in 2016–2018: a class component with a static data method.
// The same file runs twice: on the server (to HTML) and in the browser (hydration).
import { Component } from "react";

const FILTERS = { all: "All", active: "Active", done: "Done" };

export default class TodoPage extends Component {
  // Called on the server before the first render; what it returns becomes the page's props.
  // A real page would read a database or an API here.
  static async getInitialProps() {
    return {
      todos: [
        { id: 1, title: "Read the docs", done: true },
        { id: 2, title: "Write the app", done: false },
      ],
    };
  }

  constructor(props) {
    super(props);
    // The first state comes only from props, so the server and the browser render the same HTML.
    this.state = { todos: props.todos, filter: "all", title: "" };
    this.nextId = Math.max(0, ...props.todos.map((t) => t.id)) + 1;
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({ title: event.target.value });
  }

  handleSubmit(event) {
    event.preventDefault();
    const title = this.state.title.trim();
    if (!title) return;
    const todo = { id: this.nextId++, title, done: false };
    this.setState((state) => ({ todos: [...state.todos, todo], title: "" }));
  }

  toggle(id) {
    this.setState((state) => ({
      todos: state.todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)),
    }));
  }

  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">
          {shown.map((todo) => (
            <li key={todo.id} className={todo.done ? "done" : undefined}>
              <label>
                <input
                  type="checkbox"
                  data-toggle
                  checked={todo.done}
                  onChange={() => this.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={() => this.setState({ filter: name })}
              >
                {label}
              </button>
            ))}
          </div>
        </div>
      </main>
    );
  }
}

Hooks

React 19.3.0, React DOM 19.3.0

/src/App.jsx · 73 lines

JSX
// 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>
  );
}