Skip to content

Choosing State Structure

The Course
•
20 min study

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.

A selection that goes stale React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import { starterCards } from "./data.js"; export default function App() { const [cards, setCards] = useState(starterCards); const [selectedCard, setSelectedCard] = useState(starterCards[0]); function rename(id) { setCards(cards.map((card) => (card.id === id ? { ...card, title: card.title + "!" } : card))); } return ( <main> <h1>Study Board</h1> <ul className="cards"> {cards.map((card) => ( <li key={card.id} className={card.id === selectedCard.id ? "card selected" : "card"}> <button className="title" onClick={() => setSelectedCard(card)}>{card.title}</button>{" "} <button onClick={() => rename(card.id)} aria-label={`Rename ${card.title}`}>Add !</button> </li> ))} </ul> <section className="panel"> <h2>Selected: {selectedCard.title}</h2> <p className="muted">{selectedCard.minutes} minutes</p> </section> </main> ); } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then 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:

JavaScript
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:

JavaScript
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:

JavaScript
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:

JavaScript
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

Exercise

Which principle?

Each line describes some state. Say which principle it breaks, and how you'd store it instead.

  1. selectedCards, an array of whole card objects for a multi-select.
  2. isOpen and isClosed for a dialog.
  3. cardCount, kept in state next to cards.
  4. 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
  1. Duplication. Store selectedIds, an array or a Set of ids, and look the cards up during render.
  2. Contradiction. One boolean, isOpen, is enough: closed is !isOpen.
  3. Redundant. Use cards.length during render.
  4. Deep nesting. Keep a flat cards array where each card has a column id, and checklist items in their own list with a cardId.

Was this article helpful?

Your response is saved on this device.