jQuery → React and the virtual DOM
2006 – today · 2013 – today
What changed
- Where the state lives
jQuery
In the DOM: a todo is done when its
<li>has the classdone, and the counter is found by counting elements.React and the virtual DOM
In
this.stateof the topAppclass: the todos, the filter and the typed text, changed only throughthis.setState.- How the page is rendered
jQuery
The server sends the first HTML. New items are built with
$("<li>")and appended.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.- What happens on a change
jQuery
Each handler changes the elements it knows about, then
refresh()fixes the counter and the filter.React and the virtual DOM
A bound handler calls
this.setState; React merges the change into the state and callsrender()again.- How the code is organised
jQuery
One script of event handlers. A delegated handler on
#todo-listalso covers items added later.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.
Why it changed
What hurt in each era along the way, and the era that came next.
jQuery→MVC in the browser (Backbone)
When the data lives only in the DOM, every feature reads and writes the page directly: the counter counts
<li>elements, the filter checks classes. As apps grew, handlers changing the page from many places became hard to follow ("jQuery spaghetti"), and there was no model of the data to test, save or reuse. Libraries like Backbone moved the data into models and kept the page in views.MVC in the browser (Backbone)→Two-way binding (AngularJS)
Backbone left the wiring to you. Every view subscribed to its models by hand, chose what to redraw and read form fields back itself, so much of the code only connected data to the DOM. A view thrown away without
remove()stayed subscribed and kept reacting as a "zombie view", and re-rendering a template replaced elements, losing focus and half-typed text. AngularJS answered with two-way data binding: the HTML declares what shows what, and the framework keeps the page and the data in sync.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 asetTimeoutcallback 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.
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.
jQuery
jQuery 4.0.0
/src/main.js · 52 lines
// jQuery era: the page itself is the state. Handlers read the DOM, change it, recount.
import $ from "jquery";
// $(fn) waits until the document is ready, like $(document).ready(fn).
$(function () {
let filter = "all";
// Brings the counter, the visible items and the filter buttons in line with the DOM.
function refresh() {
const left = $("#todo-list li").not(".done").length;
$("#todo-count").text(left + " left");
$("#todo-list li").each(function () {
const done = $(this).hasClass("done");
$(this).toggle(filter === "all" || (filter === "done") === done);
});
$("[data-filter]").removeClass("selected");
$('[data-filter="' + filter + '"]').addClass("selected");
}
$("#todo-form").on("submit", function (event) {
event.preventDefault();
const title = String($("#new-todo").val()).trim();
if (!title) return;
// Build the new <li> the same way the server wrote the first ones.
const $item = $("<li>").append(
$("<label>").append(
$('<input type="checkbox" data-toggle>'),
" ",
$('<span class="title">').text(title),
),
);
$("#todo-list").append($item);
$("#new-todo").val("");
refresh();
});
// One delegated handler on the list also covers the items added later.
$("#todo-list").on("change", "[data-toggle]", function () {
$(this).closest("li").toggleClass("done", this.checked);
refresh();
});
$(".filters").on("click", "[data-filter]", function () {
filter = $(this).data("filter");
refresh();
});
refresh();
});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>
);
}
}