Skip to content
FrontDepth, Home

Flux and Redux → Signals and fine-grained reactivity

2014 – today · 2021 – today

Older era
Newer era
Compare

What changed

Where the state lives

Flux and Redux

In one Redux store: { todos, filter }, built by two reducers joined with combineReducers. Only the half-typed text stays in the input, read through a ref.

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

Flux and Redux

React still renders the components; connect renders TodoApp again when the props it maps from the store change.

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

Flux and Redux

A handler calls a prop like onToggle(id), which dispatches toggleTodo(id); the reducer returns a new state and the store notifies its subscribers.

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

Flux and Redux

Action types and creators, reducers, the store setup and a connected function component, each in its own file.

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

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

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

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

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

Flux and Redux
Signals and fine-grained reactivity

Flux and Redux

React 19.3.0, React DOM 19.3.0, Redux 5.0.1, React Redux 9.3.1

/src/App.jsx · 91 lines

JSX
// A container component: it owns no data. connect() passes it the store's state and the actions as props.
// JSX then compiled to React.createElement, so React had to be imported; the automatic runtime used here does not need it.
import React from "react";
import { connect } from "react-redux";
import { addTodo, toggleTodo, setFilter } from "./actions.js";

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

// A plain function of props, as in the Redux docs of the time: the typed text is read from
// the input through a ref, so the component needs no state of its own.
function TodoApp({ todos, left, filter, onAdd, onToggle, onFilter }) {
  let input;

  function handleSubmit(event) {
    event.preventDefault();
    const title = input.value.trim();
    if (!title) return;
    onAdd(title);
    input.value = "";
  }

  return (
    <main className="todo-app">
      <h1>Todos</h1>
      <form id="todo-form" onSubmit={handleSubmit}>
        <input
          id="new-todo"
          ref={(node) => {
            input = node;
          }}
          placeholder="What needs doing?"
          autoComplete="off"
          aria-label="New todo"
        />
        <button id="add" type="submit">
          Add
        </button>
      </form>
      <ul id="todo-list">
        {todos.map((todo) => (
          <li key={todo.id} className={todo.done ? "done" : undefined}>
            <label>
              <input
                type="checkbox"
                data-toggle
                checked={todo.done}
                onChange={() => onToggle(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.keys(FILTERS).map((name) => (
            <button
              key={name}
              type="button"
              data-filter={name}
              className={filter === name ? "selected" : undefined}
              onClick={() => onFilter(name)}
            >
              {FILTERS[name]}
            </button>
          ))}
        </div>
      </div>
    </main>
  );
}

// Picks what the component reads from the state. Derived values are computed, not stored.
const mapStateToProps = (state) => ({
  todos: state.todos.filter((t) => state.filter === "all" || (state.filter === "done") === t.done),
  left: state.todos.filter((t) => !t.done).length,
  filter: state.filter,
});

// The component never changes data itself: its callbacks dispatch actions to the store.
const mapDispatchToProps = (dispatch) => ({
  onAdd: (title) => dispatch(addTodo(title)),
  onToggle: (id) => dispatch(toggleTodo(id)),
  onFilter: (name) => dispatch(setFilter(name)),
});

// connect() subscribes to the store, runs mapStateToProps when the state changes and renders
// TodoApp again when the result differs. @deprecated since React-Redux 9.3 (hooks are
// recommended), it still works the same and prints nothing (legacy_connect is the same).
export default connect(mapStateToProps, mapDispatchToProps)(TodoApp);

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