The previous lesson in this module covered updating lists without rebuilding them, and this one moves one level up. It looks at the state that your app remembers between one person action and the next, such as which items are in the basket, which tab is open, and what has been typed but not yet saved. In plain JavaScript the temptation is to leave that state in the page itself, because the page is already there. This lesson argues for keeping it in a plain object instead, and shows the small amount of machinery that makes that pay off. The last lesson in this module then puts the pieces together into a small user interface.
Why is the page a bad place to keep your app's state?
It starts out innocently. The text inside a <span> is the item count, so you read it back when you need the count. The checked property of a checkbox is the answer to a question, so you read it back when you need the answer. It works until two places need the same fact and only one of them updates it.
Reading state out of the page has three problems, and they make each other worse. The value lives somewhere that you have to go and look for, so there is no single place to look when something goes wrong. Two widgets can disagree with each other, because nothing guarantees that updating one of them updates the other. And the page is only a drawing of your data, so treating the drawing as the data means that every change to the data has to be expressed as a change to the markup, which is a lot of round trips for one simple fact.
The alternative is a plain JavaScript object that holds the facts, with the page treated as a result of that object. When the object changes, the page is redrawn from it. The object is the source of truth, and the markup is a consequence of it.
What does a single source of truth look like in plain JavaScript?
It is an ordinary object. There is nothing exotic about it, no framework, and no magic reactivity. What makes it a source of truth is a discipline. Every fact lives in exactly one place, and every change to that place goes through a single function, so that anything interested can find out that it happened.
function createStore(initialState) {
let state = initialState;
const listeners = new Set();
return {
getState: function () {
return state;
},
setState: function (next) {
state = { ...state, ...next };
for (const listener of listeners) {
listener(state);
}
},
subscribe: function (listener) {
listeners.add(listener);
return function () {
listeners.delete(listener);
};
},
};
}
const store = createStore({ query: "", items: [] });
function report(state) {
console.log("changed:", state.query);
}
const unsubscribe = store.subscribe(report);
store.setState({ query: "books" });
unsubscribe();
store.setState({ query: "games" });
console.log(store.getState().query); // "games"
There are three pieces here, and each one earns its place. getState is the only way to read the current facts. setState merges a patch into the current state and then tells every listener. subscribe registers a listener and hands back a function that removes it again, which is what you use when a component is torn down.
Notice the merge. The call setState({ query: "books" }) does not replace the whole object, because it merges the given keys over the current ones, so items is left alone. That is what stops a caller from accidentally wiping fields that it never mentioned.
Should a state update create a new object or change the old one?
Creating a new object is the better habit, and the reason is comparison. If every update produces a fresh top-level object, then the question "has the state changed?" is answered by oldState !== newState, and you can skip an expensive redraw when nothing actually changed. If you change the object in place, then that question cannot be answered without comparing every field by hand.
A new object does not mean a deep copy. The parts that you did not touch can be shared, and that is exactly what keeps updates cheap.
const snapshot = { user: { name: "Ada", tags: ["admin"] } };
// Changing it in place changes the very object that everyone is holding.
const original = snapshot;
original.user.name = "Grace";
console.log(original === snapshot); // true, it is literally the same object
// Building a new object leaves the old snapshot alone.
const updated = { ...snapshot, user: { ...snapshot.user, name: "Hopper" } };
console.log(snapshot.user.name); // "Grace", the old snapshot is untouched
console.log(updated.user.name); // "Hopper"
console.log(updated.user.tags === snapshot.user.tags); // true, untouched parts are shared
The last line is the one that makes this practical. A shallow spread copies the references to the parts that you are not changing, so updating a nested object means spreading that nested object as well, and everything below it stays shared. Deep-cloning the whole tree on every keystroke would be far more expensive, and it would break exactly the reference comparisons that make change detection possible.
Which values should you compute instead of storing?
Any value that can be worked out from other state should not be stored at all. A total, a filtered list, a count of selected items, and a simple answer such as "is the form dirty" are all functions of the facts that you already hold. Storing them creates a second copy that can drift out of step with the first, and then you have a bug where the heading says three items while the basket contains four.
Keep the calculation inside a small set of named functions and call it where you need it. Those functions double as documentation of what the state actually means.
const cartState = {
items: [
{ id: 1, name: "Notebook", price: 600, qty: 2 },
{ id: 2, name: "Pen", price: 100, qty: 5 },
],
taxRate: 0.1,
};
function itemCount(state) {
let count = 0;
for (const item of state.items) {
count = count + item.qty;
}
return count;
}
function subtotal(state) {
let total = 0;
for (const item of state.items) {
total = total + item.price * item.qty;
}
return total;
}
function total(state) {
return Math.round(subtotal(state) * (1 + state.taxRate));
}
// Derived values are worked out on demand and never stored.
console.log(itemCount(cartState)); // 7
console.log(subtotal(cartState)); // 1700
console.log(total(cartState)); // 1870
Storing money in whole pence rather than in pounds is not a style preference. Floating point arithmetic does not represent 0.1 exactly, so adding up decimal prices produces values such as 18.700000000000003. Rounding once, at the end, is a habit that is worth forming early.
How should you shape the state object?
Keep it flat and shallow. A state object that reads like a summary of the screen, with one key for each meaningful thing that the app knows, is easy to reason about and easy to log when something goes wrong. Deeply nested structures look tidy, but they make every update a multi-step spread, and the place where you end up storing a derived value is usually somewhere nested.
const appState = {
filters: { query: "", sort: "name" },
selection: [],
isSaving: false,
};
// A flat slice is only one spread away from a new object.
const nextAppState = {
...appState,
filters: { ...appState.filters, query: "js" },
};
console.log(nextAppState.filters.query); // "js"
console.log(appState.filters.query); // "", the old state is untouched
console.log(nextAppState.selection === appState.selection); // true, other slices are shared
Two habits make this maintainable. Give every piece of state a name that says what it means, such as isSaving instead of flag, because you will read this object far more often than you will write to it. And resist the temptation to add a field that simply mirrors an existing one, because if a value can be computed then it belongs in a function like the ones above.
How does the page follow the state?
Once the state is separate, rendering becomes a function that you call whenever the state changes. The simplest version assigns a new state and then calls render, while the store version calls render from a subscriber. The important part is that render only reads from the state and only writes to the page, so it can be called as often as you like without any surprises.
const cartList = document.querySelector("#cart");
let viewState = { items: [{ id: 1, name: "Notebook", qty: 2 }] };
function render() {
cartList.replaceChildren();
for (const item of viewState.items) {
const row = document.createElement("li");
row.textContent = item.name + " x" + item.qty;
cartList.append(row);
}
}
render();
viewState = { items: [...viewState.items, { id: 2, name: "Pen", qty: 5 }] };
render();
console.log(cartList.querySelectorAll("li").length); // 2
console.log(cartList.querySelector("li").textContent); // "Notebook x2"
For a long list you would want the incremental approach that the earlier lesson covered, rather than the replaceChildren call above, but the structure is exactly the same. The state changes, then the render runs, and the render reads the state and writes the page. Nothing else is allowed to write to the page, and that is what stops you from ending up with two sources of truth wearing different clothes.
The plain-JavaScript state reference
createStore(initialState)gives you a state object, a merge-basedsetState, and subscribers.store.getState()is the only way to read the current facts.store.subscribe(fn)returns an unsubscribe function.{ ...state, ...patch }merges a change into a new object, and you spread the nested slices as well.total(state)computes a derived value on demand rather than storing it.render()is the only function that is allowed to write to the page.
Try it yourself: build a page with a basket of three items and a total. Keep the items in one object, and keep the total inside a function rather than inside a variable. Add a button that increases the quantity of the first item, and make sure that the total updates without you touching it by hand. Then add a derived answer such as hasItems, and confirm that you can delete it and recompute it at any time without breaking anything.