Knowing what is state is half the job. The other half is its shape. Badly shaped state compiles and runs, then shows wrong data in a corner case. Here is one such bug.
Predict: a stale selection
Click Read about reducers to select it. Then press Add ! next to it twice. Before you do, predict what the Selected panel will say.
npm install and npm run dev. Check your prediction
The list says Read about reducers!!, but the panel still says Selected:
Read about reducers. selectedCard still refers to the old object from
the moment you clicked. rename replaces that card with a new object in
cards; it doesn't change the old object. State now has two versions of the
same card, and they disagree:
const [selectedCard, setSelectedCard] = useState(starterCards[0]);
function rename(id) {
setCards(cards.map((card) => (card.id === id ? { ...card, title: card.title + "!" } : card)));
}Principle 1: don't duplicate data
Store the id of the selected card, and look the card up during render:
const [selectedId, setSelectedId] = useState(starterCards[0].id);
const selectedCard = cards.find((card) => card.id === selectedId);Now there's one copy of each card, in cards. The selection is just a
pointer to it, so it can't go stale. Make the change, updating the two places
that used setSelectedCard and selectedCard.id, and repeat the experiment.
Principle 2: avoid contradictions
Two booleans that must never both be true are a bug waiting to happen:
const [isSaving, setIsSaving] = useState(false);
const [isSaved, setIsSaved] = useState(false);Forget to reset one, and the screen says "Saving…" and "Saved" at once. One value with named options can't contradict itself:
const [status, setStatus] = useState("idle"); // "idle" | "saving" | "saved"Principle 3: avoid redundant state
If a value can be computed from props or other state, compute it. A stored copy has to be updated everywhere the original changes, and sooner or later one place is missed. The next lesson shows exactly that bug.
Principle 4: group what changes together
Values that always change at the same moment, like an x and a y, belong in
one object. Values that change independently, like the search text and the
selection, are clearer as separate useState calls.
Principle 5: avoid deep nesting
Deeply nested state, such as columns that contain cards that contain
checklists, makes every update a stack of spreads. A flat list of cards that
each name their column, as in data.js, keeps updates to a single map. This
is called normalizing state, the way a database stores rows that point to
each other by id.
Your turn
Which principle?
Each line describes some state. Say which principle it breaks, and how you'd store it instead.
selectedCards, an array of whole card objects for a multi-select.isOpenandisClosedfor a dialog.cardCount, kept in state next tocards.board = { columns: [{ id, cards: [{ id, title, checklist: [...] }] }] }.
Hint 1: the idea
Choose one source for each fact. Store a choice or an input, then calculate the values that follow from it.
Hint 2: a first step
For each, ask: is the same information stored twice? Can two values disagree? Can it be computed? Does an update need several nested spreads?
Show one solution
- Duplication. Store
selectedIds, an array or aSetof ids, and look the cards up during render. - Contradiction. One boolean,
isOpen, is enough: closed is!isOpen. - Redundant. Use
cards.lengthduring render. - Deep nesting. Keep a flat
cardsarray where each card has acolumnid, and checklist items in their own list with acardId.
Completion is saved in this browser only. It does not measure mastery.