Chapter 9 Β· Managing State

Structuring & Sharing State

As apps grow, how you organise state matters more than anything else. Good structure prevents most bugs.

You will learn
  • How to think in states instead of step-by-step instructions
  • Five principles for choosing your state structure
  • How to lift state up to share it between components
  • Controlled vs uncontrolled components

Reacting to input with state

With plain JavaScript you write instructions: "disable the button, show the spinner, hide the form…". In React you describe the different visual states your UI can be in, and switch between them by changing state.

Think of a quiz form. Work through it in five steps:

Step 1: list the visual states

Step 2: what triggers the changes?

Human inputs (typing, clicking Submit) and computer inputs (the network response arrives, success or failure).

Step 3: represent it with as little state as possible

Instead of several booleans (isTyping, isSubmitting, isSuccess…) that could contradict each other, one status can only ever be one value at a time.

Step 4: render each state

Step 5: connect the event handlers

That's what handleSubmit and onChange do above. Notice there's no "disable the button" code anywhere. The button is disabled because of the state.

Five principles for structuring state

1. Group related state

If two values always change together, put them in one object:

2. Avoid contradictions

3. Avoid redundant state: calculate during render

If you can compute a value from props or other state, don't store it:

Don't copy props into state The only reason to copy a prop is to deliberately ignore later changes. Name it to make that clear: initialColor.

4. Avoid duplication: store IDs, not copies

5. Avoid deep nesting

Deeply nested state is painful to update (remember all the copying in Chapter 8). Consider a flat structure, where items reference each other by ID, like database tables.

The goal Make state as simple as possible, but no simpler. Store the minimum, and calculate everything else.

Sharing state between components: lifting state up

Sometimes two components need the same data. Example: an accordion where only one panel can be open at a time.

Before: each panel has its own state

The panels can't coordinate, so both can be open at once.

After: move the state up to the common parent

There are three steps:

  1. Remove the state from the children.
  2. Pass the data down from the parent as props.
  3. Add the state to the parent, and pass down event handlers so the children can ask for changes.

Data flows down as props, and requests to change it flow up through event handler props. This is the pattern you'll use most in React.

Controlled vs uncontrolled

After lifting the state up, Panel is controlled by Accordion.

A single source of truth Every piece of state should live in exactly one component. To decide which one, find the closest common parent of all the components that need it.

More examples

Example 1: search, storing the query only

Example 2: tabs with lifted state

Example 3: temperature converter (two inputs, one source of truth)

Both inputs show the same piece of state, converted. Editing either one updates celsius.

Example 4: a selected item stored by ID

Recap

  • Think in visual states, and prefer one status over many booleans.
  • Group related state, avoid contradictions, don't store what you can calculate, store IDs instead of copies, and keep it flat.
  • To share state, lift it up to the closest common parent and pass it down with props and handlers.

Exercises

1. Synced inputs

Render two <Input label="First" /> and <Input label="Second" /> components so that typing in either updates both.

Show solution

2. Remove the redundant state

Show solution

3. Spot the unnecessary state 🟒 easy

Which of these should not be state?

Show answer

count (= items.length), isEmpty (= items.length === 0) and filtered (= items filtered by query) can all be calculated. Keep only items and query.

4. Booleans β†’ status 🟒 easy

Rewrite it with one state variable.

Show solution

5. FAQ accordion 🟒 easy

Render 3 FAQ items where only one answer is open at a time. Clicking an open question closes it.

Show solution

6. Lift the search box 🟑 medium

Split Example 1 into SearchBox({ query, onQueryChange }) and ResultList({ results }), with the state in the parent CitySearch.

Show solution

7. km ↔ miles 🟑 medium

Like the temperature converter: two inputs, kilometres and miles (1 km = 0.621371 mi), with only one piece of state.

Show solution

8. Select and edit 🟑 medium

Show a list of notes on the left. Clicking one selects it (stored by ID) and shows a textarea on the right to edit its text. The list should update live as you type.

Show solution

9. A fake "send" with status 🟑 medium

Make a message form with a status of 'typing', 'sending' or 'sent'. On submit, set it to 'sending', then use setTimeout to set it to 'sent' after 1.5 seconds. Disable the input and button while sending, and show "βœ… Sent!" at the end.

Show solution

10. Shopping list + summary πŸ”΄ hard

Build three sibling components, AddItemForm, ItemList and Summary ("3 items, 2 bought"). Ticking an item in ItemList must update Summary. Decide where the state lives, and pass down the data and handlers.

Show solution

Notice the draft text in AddItemForm stays local. Only lift state that other components actually need.