Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 18.2 — Managing Focus
React · Example 1 of 3 React 19+

Focus the new page's heading after navigation

Without the effect, focus would stay on the Cart link and a screen reader would say nothing about the new page. Try Tab from the top of the preview: the skip link appears first.

Keyboard and screen reader users follow focus, so when React swaps content, changes the route or opens a modal, you must decide where focus goes: to the new page's heading, into the dialog, and back to the button that opened it.

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 6 hands-on exercises with automatic checks.

Practice questions

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

01

Write a useFocusOnChange(ref, value) hook that focuses ref.current whenever value changes, but not on the first render.

02

Write the effect for a custom popover that remembers the opener when it opens and restores focus when it closes.

Explain it without notes

01

Why do single-page apps need explicit focus management on route changes, and how would you implement it?

02

List everything an accessible modal must do with focus, and say which parts <dialog> with showModal() gives you.

03

What happens to focus when React unmounts the focused element, and how do you handle it?

04

What is a skip link and why does its target need tabIndex={-1}?

Focus the new page's heading after navigation React 19+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

on load, focus is on: BODY
after navigating, focus is on: H1 Your cart
document.title: Your cart | Shop
after skip link: MAIN main