Chapter 9 Β· Managing State
Structuring & Sharing State
As apps grow, how you organise state matters more than anything else. Good structure prevents most bugs.
- 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
- empty: the form has a disabled Submit button
- typing: the form has an enabled Submit button
- submitting: everything is disabled and a spinner shows
- success: a "Thank you!" message replaces the form
- error: like typing, plus an error message
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:
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.
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:
- Remove the state from the children.
- Pass the data down from the parent as props.
- 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
- An uncontrolled component keeps its own local state. It's easy to use, but the parent can't influence it.
- A controlled component gets its important data from props. It's more flexible, because the parent is in charge.
After lifting the state up, Panel is controlled by Accordion.
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
statusover 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.
π Official docs: Reacting to Input with State Β· Choosing the State Structure Β· Sharing State Between Components