Why draw the UI from data?
Two truths, a predictable screen, and the idea React is built on.
<li>, delete — remove the <li>, add — append an <li>. A week later the counter said "−1 tasks left". For a year I thought that was philosophy. Turned out it was a bug.1. One truth instead of two. If the data lives both in an array and in the DOM, you have two copies of one truth. Every handler has to update both — and every place they're shown: the item, the counter, the tab title, the "3 new" badge. Forget one place and the copies drift apart. When there's one truth (the state) and the DOM is always derived from it, there's nothing to drift.
2. The screen is a function of the data. render(state) always draws the same thing for the same data. It doesn't matter which clicks led there: five additions and two deletions, or a load from localStorage. The screen depends only on *what there is now*, not on the *history* of how you got there. History is hard to keep in your head; "what there is now" is easy.
function view(todos, filter) {
return todos
.filter((todo) => filter === "all" || (filter === "done") === todo.done)
.map((todo) => (todo.done ? "[x] " : "[ ] ") + todo.title);
}
const todos = [
{ id: 1, title: "Buy cat food", done: true },
{ id: 2, title: "Take a nap", done: false },
];
console.log(view(todos, "all"));
console.log(view(todos, "active"));
console.log(view(todos, "all"));3. A bug can be reproduced. A user writes "it broke for me". If everything is described by state, ask for the JSON from localStorage, load it — and you see exactly the same screen. With a hand-edited DOM that trick won't work: the state is smeared across a hundred elements.
4. New features get cheaper. Want a "Done" filter? That's one state variable and one line in render(). No hunting for every handler that hides and shows things.
Where it came from. In the jQuery era (the late 2000s) interfaces were written exactly like that — every handler patched the DOM by hand. When apps grew to Facebook size, it became unbearable: the unread-messages counter in one corner disagreed with the list in another. In 2013 Facebook open-sourced React, built on a simple formula: UI = f(state). Vue, Svelte and the rest arrived at the same idea.
Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.