Skip to content
FrontDepth, Home

React and the virtual DOM → Flux and Redux

2013 – today · 2014 – today

Older era
Newer era
Compare

What changed

Where the state lives

React and the virtual DOM

In this.state of the top App class: the todos, the filter and the typed text, changed only through this.setState.

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.

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.

Flux and Redux

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

What happens on a change

React and the virtual DOM

A bound handler calls this.setState; React merges the change into the state and calls render() again.

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.

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.

Flux and Redux

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

Why it changed

What hurt in each era along the way, and the era that came next.

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

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
Flux and Redux

React and the virtual DOM

React 19.3.0, React DOM 19.3.0

/src/App.jsx · 98 lines

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

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