Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 6.6 — Where Each Piece of State Should Live
React · Example 1 of 2

Colocation renders less

Opening the first menu renders its SlowList again, because the state's owner contains the list. Opening the second menu renders only Dropdown. Same screen, less work, and the menu code is all in one place.

Keep state as close as possible to the components that use it (colocation), lift it only as far as needed to share it, and recognise the special kinds that belong elsewhere: server data in a cache, shareable UI in the URL, and form drafts in the form.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

An App component holds const [isSearchOpen, setIsSearchOpen] = useState(false) and passes it down three levels to a SearchButton, which is the only component that uses it. Where should it live? Rewrite SearchButton.

02

Make a paginated list whose page number lives in the URL (?page=2) using useSearchParams, with Previous and Next buttons.

Explain it without notes

01

What is state colocation and why is it a good default?

02

Name the kinds of state in a typical app and where each usually lives.

03

When should state live in the URL? What should you watch out for?

04

Why is server data treated differently from other state?

Colocation renders less

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

too high: SlowList rendered
colocated: SlowList rendered
--- opening both menus ---
too high: SlowList rendered