Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 132 ยท State and Events

Choosing a State Structure

Learn how to structure React state - group related values, avoid contradictions, redundancy and duplication, flatten deep nesting and normalize data, with step-by-step refactors.

Most state bugs are not caused by clever code. They are caused by a state shape that allows the wrong thing to happen: two variables that can disagree, a copy of data that goes stale, an object nested so deeply that updating it takes ten lines. If you design the shape well, the code that updates it becomes short, and many bugs become impossible to write.

This lesson gives you five rules for deciding what goes into useState and how to arrange it. Each rule is shown with a small component that has the problem, followed by the fix. You should already be comfortable with useState and updating objects and arrays.

A useful opening question for any piece of data is: is this really state? State is information that changes over time and cannot be calculated from anything else React already has. Everything else is a prop, a constant or a value you compute while rendering.

Rule 1: group state that changes together

If two variables are always updated at the same moment, they are one thing. Keeping them in separate useState calls means you have to remember to update both, and one day you will forget.

Imagine a draggable dot. The x and y always move together:

JSX
const [x, setX] = useState(0);
const [y, setY] = useState(0);

A single object removes the chance of updating one and not the other:

Grouped position state

The same applies to form fields (see controlled forms): a form with a dozen fields is one values object, not twelve variables. The counter-rule is equally important: do not group things that change independently. A isOpen flag and a searchText string have nothing to do with each other, so give them separate state.

If you cannot decide, ask: "Would I ever update one without the other?" If yes, keep them apart. If never, group them.

Rule 2: avoid contradictions

Look at this state for a "send message" form:

JSX
const [isSending, setIsSending] = useState(false);
const [isSent, setIsSent] = useState(false);

Two booleans give four combinations, but only three of them mean anything: typing, sending, sent. The fourth, isSending and isSent both true, is a contradiction. Nothing stops your code from reaching it, and the UI will show something nonsensical when it does.

Replace the pair with one status variable that can only hold one value at a time.

One status instead of two booleans

You can still have convenient booleans such as isSending: just compute them from status during render, as above. Now the component cannot be "sending" and "sent" at once, because there is only one variable. When you notice yourself writing "this should never happen" comments, it is a signal to restructure so that it cannot happen. State machines in React takes this idea to its conclusion.

Rule 3: avoid redundant state

If a value can be calculated from props or other state, calculate it. Storing it means every update has to touch both copies:

JSX
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [fullName, setFullName] = useState(''); // redundant

Whoever forgets to call setFullName creates a bug. Delete the third variable and write const fullName = firstName + ' ' + lastName; in the body. It is recomputed each render, which is cheap and always correct. (For genuinely expensive work see useMemo.)

The same mistake appears with lists: keeping both items and visibleItems (the filtered version), or both items and totalCount. Keep the source, derive the rest.

Derived values instead of redundant state

There are only two pieces of state, items and onlyMissing. The count and the visible list are variables computed in the body, so they can never be out of date.

A special case: props copied into state

Copying a prop into state is the redundant-state mistake in disguise:

JSX
function Message({ messageColor }) {
  const [color, setColor] = useState(messageColor);
  // ...
}

useState only uses its argument on the first render. When the parent later passes a new messageColor, color keeps the old value. If you want the prop, read the prop. Copying is correct only when you intend the prop to be an initial value and ignore later changes; then name it that way (initialColor). To reset such state when something identifying changes, give the component a key, as covered in useState.

Rule 4: avoid duplication

Duplication happens when the same object lives in two places in state. The classic case is a "selected item":

JSX
const [items, setItems] = useState(initialItems);
const [selectedItem, setSelectedItem] = useState(items[0]); // a copy of an object

When you rename an item in items, selectedItem still points to the old object, and the screen shows stale text. Store the id instead, and look up the object during render.

Selection by id, not by copy

Edit the name in the box: the list and the heading below it update together, because there is exactly one copy of each contact. If the selected item could be deleted, find would return undefined, so handle that case (reset selectedId in the same event handler that deletes).

Rule 5: avoid deeply nested state

A tree of nested objects is hard to update, because an immutable change means copying every level between the root and the thing you changed:

JSX
setPlan({
  ...plan,
  [parentId]: {
    ...plan[parentId],
    childPlaces: plan[parentId].childPlaces.map((child) =>
      child.id === id ? { ...child, visited: true } : child
    ),
  },
});

The fix is to flatten or normalize the data, the way a database does. Store every entity once in a flat object (a lookup table) by id, and let parents refer to their children by id.

JSX
const [places, setPlaces] = useState({
  0: { id: 0, title: '(root)', childIds: [1, 2] },
  1: { id: 1, title: 'Earth', childIds: [3] },
  2: { id: 2, title: 'Moon', childIds: [] },
  3: { id: 3, title: 'Europe', childIds: [] },
});

Now changing one place touches only one entry: setPlaces({ ...places, 3: { ...places[3], title: 'EU' } }). The whole tree still renders, by looking each child up from its parent's childIds.

A normalized tree you can prune

Removing "Earth" is a one-entry change: the parent's childIds loses the id, and the subtree disappears from the screen. (The detached entries still sit in places; real code can clean them up too, and a normalized store usually does so in one function.) Normalization is the same idea you will meet again in reducers and in state management libraries.

For modestly nested state, an alternative to flattening is a helper such as Immer, which lets you write "mutating" code that produces an immutable update. It is covered in objects and arrays in state. Flattening is still the better first move, because it also makes the data easier to render and reason about.

A step-by-step refactor

Here is how the rules combine. A shopping basket starts out like this:

JSX
const [items, setItems] = useState([...]);
const [total, setTotal] = useState(0);          // redundant (rule 3)
const [selectedItem, setSelectedItem] = useState(null); // duplicate (rule 4)
const [isLoading, setIsLoading] = useState(false);
const [hasError, setHasError] = useState(false); // contradicts isLoading (rule 2)

Walk through it:

  1. total is derivable: delete it and compute items.reduce(...) in render.
  2. selectedItem holds a copy: replace it with selectedId and use find.
  3. isLoading plus hasError allow "loading and failed": replace both with status ('idle' | 'loading' | 'error' | 'ready').

You went from five variables to three (items, selectedId, status), each one independent, and every other fact is computed from them.

When to deviate

These are guidelines, not laws. Sometimes you keep a derived value in state on purpose, for example a snapshot of data taken at a moment in time (a "draft" copy while editing, so that Cancel restores the original). Sometimes a deep structure is the honest shape of the data and a library such as Immer is the practical answer. The point is to choose consciously, and to notice that every extra piece of state is another thing that can drift out of sync.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A component has isLoading and isError booleans, both set by hand. What is the main risk?

    Two booleans create four combinations, some meaningless. A single status value such as 'idle', 'loading' or 'error' makes the impossible combinations unrepresentable.
  2. 2. You store items and also visibleItems (the filtered list) in state. What should you do?

    Anything that can be calculated from other state is redundant. Derive it in the component body so it can never be stale.
  3. 3. Why is storing selectedItem (an object copied from items) risky?

    The copy and the list entry are different objects. Updating one does not update the other. Store the id and look the object up while rendering.
  4. 4. What does normalizing nested state mean?

    A flat structure makes each update touch a single entry and removes duplicated copies.
  5. 5. const [color, setColor] = useState(props.color) ignores later changes to the prop. Why?

    The initial value is read once. Copying a prop into state is only right when you want an initial value; otherwise use the prop directly.

Summary

  • State is data that changes over time and cannot be calculated from other data; everything else is derived in render.
  • Group values that always change together, but keep independent values separate.
  • Replace boolean flags that can contradict each other with a single status variable.
  • Do not store what you can compute (totals, filtered lists, full names), and do not copy props into state unless you mean "initial value".
  • Store ids instead of duplicate objects, and flatten or normalize deeply nested data so each update touches one place.
  • Each extra piece of state is a chance for the pieces to disagree, so keep the minimum.

Next: Lifting State Up and Sharing State