MVC in the browser (Backbone) → Hooks
2010 – today · 2018 – today
What changed
- Where the state lives
MVC in the browser (Backbone)
In models: every todo is a
Backbone.Modelin aCollection, and the filter sits in a model of its own (ui).Hooks
In
useState: the list lives in theuseTodos()hook, the filter and the text field in the component.- How the page is rendered
MVC in the browser (Backbone)
Each
TodoViewrenders its own<li>from an_.template; the app view updates only the counter and the filter buttons.Hooks
React renders the whole
Appfrom state on every change and updates only the DOM that differs.- What happens on a change
MVC in the browser (Backbone)
A handler calls
set()on a model; the model fireschange, and every view listening to it re-renders itself.Hooks
A handler calls a setter with a new array; React re-runs the component and recomputes
shownandleft.- How the code is organised
MVC in the browser (Backbone)
Models, a collection and views connected by events. A view's
eventshash delegates DOM events to its element.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.
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.
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,
setStatecalls 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.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/mapDispatchToPropsto 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.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.
SSR, SSG and meta-frameworks→Hooks
Pages now arrived rendered, but the components were still classes: one feature's logic was spread over
componentDidMount,componentDidUpdateandcomponentWillUnmount, sharing stateful logic needed higher-order components or render props, and every handler had to be bound tothis(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.
MVC in the browser (Backbone)
Backbone 1.6.1, Underscore 1.13.8, jQuery 4.0.0
/src/main.js · 100 lines
// Backbone era: the data lives in models. Views listen to them and re-render themselves.
import Backbone from "backbone";
import _ from "underscore";
import $ from "jquery";
// A model keeps attributes; set() changes one and fires "change:done", then "change".
const Todo = Backbone.Model.extend({
defaults: { title: "", done: false },
toggle: function () {
this.set("done", !this.get("done"));
},
});
// A collection is an ordered list of models and passes their events on.
const TodoList = Backbone.Collection.extend({
model: Todo,
remaining: function () {
return this.where({ done: false });
},
});
const todos = new TodoList([
{ title: "Read the docs", done: true },
{ title: "Write the app", done: false },
]);
// The filter is state too, so it lives in a model that views can listen to.
const ui = new Backbone.Model({ filter: "all" });
// Compiled once into a function. <%- %> escapes the title, <%= %> writes HTML as it is.
const itemTemplate = _.template(
'<label><input type="checkbox" data-toggle<%= done ? " checked" : "" %>> ' +
'<span class="title"><%- title %></span></label>',
);
// One view per todo: it owns its <li> and redraws it whenever the model changes.
const TodoView = Backbone.View.extend({
tagName: "li",
// Delegated to this.el, so the handler survives every re-render of the <li>.
events: { "change [data-toggle]": "toggleDone" },
initialize: function () {
// listenTo remembers each subscription, so view.remove() can drop them all. A view thrown
// away without remove() stays subscribed to ui and keeps rendering: a "zombie view".
this.listenTo(this.model, "change", this.render);
this.listenTo(ui, "change:filter", this.render);
},
render: function () {
const done = this.model.get("done");
const filter = ui.get("filter");
// New HTML replaces the checkbox, so the view has to give keyboard focus back itself.
const focused = this.el.contains(document.activeElement);
this.$el.html(itemTemplate(this.model.toJSON()));
if (focused) this.$("[data-toggle]").trigger("focus");
this.$el.toggleClass("done", done);
this.$el.toggle(filter === "all" || (filter === "done") === done);
return this;
},
toggleDone: function () {
this.model.toggle();
},
});
// The app view takes over markup that is already in the page: el is a selector.
const AppView = Backbone.View.extend({
el: ".todo-app",
events: {
"submit #todo-form": "create",
"click [data-filter]": "pickFilter",
},
initialize: function () {
this.listenTo(todos, "add", this.addOne);
this.listenTo(todos, "add change:done", this.render);
this.listenTo(ui, "change:filter", this.render);
todos.each(this.addOne, this);
this.render();
},
addOne: function (todo) {
this.$("#todo-list").append(new TodoView({ model: todo }).render().el);
},
// Renders only what this view owns: the counter and the selected filter.
render: function () {
this.$("#todo-count").text(todos.remaining().length + " left");
this.$("[data-filter]").removeClass("selected");
this.$('[data-filter="' + ui.get("filter") + '"]').addClass("selected");
return this;
},
create: function (event) {
event.preventDefault();
const $input = this.$("#new-todo");
const title = $input.val().trim();
if (!title) return;
todos.add({ title: title });
$input.val("");
},
pickFilter: function (event) {
ui.set("filter", $(event.currentTarget).data("filter"));
},
});
new AppView();Hooks
React 19.3.0, React DOM 19.3.0
/src/App.jsx · 73 lines
// 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>
);
}