Skip to content
FrontDepth, Home

Two-way binding (AngularJS) → Hooks

2010 – 2021 · 2018 – today

Older era
Newer era
Compare

What changed

Where the state lives

Two-way binding (AngularJS)

On $scope: plain objects in $scope.todos, the filter in $scope.show and the text field's value in $scope.newTitle.

Hooks

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

How the page is rendered

Two-way binding (AngularJS)

The HTML is the template: AngularJS compiles the ng-* attributes and {{ }} once, then each binding updates its own piece of the DOM.

Hooks

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

What happens on a change

Two-way binding (AngularJS)

Directives run handlers inside $apply; the digest evaluates every watcher again and changes the DOM where a value differs. ng-model also writes from the field back to the scope.

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

Two-way binding (AngularJS)

A module, a controller that fills $scope, and directives in the HTML. The controller has no DOM code.

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

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

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

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

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

Two-way binding (AngularJS)
Hooks

Two-way binding (AngularJS)

AngularJS 1.8.3

/index.html · 35 lines

HTML
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Todos · AngularJS</title>
    <link rel="stylesheet" href="/styles.css" />
  </head>
  <body>
    <!-- The page is the template: ng-* attributes and {{ }} bind it to TodoCtrl's $scope. -->
    <main class="todo-app" ng-controller="TodoCtrl">
      <h1>Todos</h1>
      <!-- A form without an action: AngularJS stops the real submit and calls add(). -->
      <form id="todo-form" ng-submit="add()">
        <!-- Two-way: typing writes $scope.newTitle, and setting newTitle changes the field. -->
        <input id="new-todo" ng-model="newTitle" placeholder="What needs doing?" autocomplete="off" aria-label="New todo" />
        <button id="add" type="submit">Add</button>
      </form>
      <ul id="todo-list">
        <!-- ng-repeat gives every <li> a child scope holding its todo. ng-model="todo.done" writes -->
        <!-- straight into that object, so the controller's list sees the change. -->
        <li ng-repeat="todo in todos | filter:matches" ng-class="{done: todo.done}">
          <label><input type="checkbox" data-toggle ng-model="todo.done" /> <span class="title">{{todo.title}}</span></label>
        </li>
      </ul>
      <div class="footer">
        <span id="todo-count">{{remaining()}} left</span>
        <div class="filters">
          <button type="button" data-filter="all" ng-class="{selected: show == 'all'}" ng-click="show = 'all'">All</button>
          <button type="button" data-filter="active" ng-class="{selected: show == 'active'}" ng-click="show = 'active'">Active</button>
          <button type="button" data-filter="done" ng-class="{selected: show == 'done'}" ng-click="show = 'done'">Done</button>
        </div>
      </div>
    </main>
  </body>
</html>

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