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 2 of 2

URL state: the address bar is the source of truth

The page opened at ?sort=price (as if from a shared link) and showed the cheapest first. Clicking a button changes the URL, and the list follows it. In a real app the Back button would undo the sort. React Router is taught in Phase 13.

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?

URL state: the address bar is the source of truth

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

URL: /products?sort=price
URL: /products?sort=name