A native <dialog> moves, traps and restores focus
The browser did the hard parts: focus moved inside (the effect then picked Cancel over the first button, Delete), the page behind refused focus, and closing put focus back on the opener. Open it yourself and press Escape: onClose keeps React's open state in step.
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.
Write a useFocusOnChange(ref, value) hook that focuses ref.current whenever value changes, but not on the first render.
Write the effect for a custom popover that remembers the opener when it opens and restores focus when it closes.
Explain it without notes
Why do single-page apps need explicit focus management on route changes, and how would you implement it?
List everything an accessible modal must do with focus, and say which parts <dialog> with showModal() gives you.
What happens to focus when React unmounts the focused element, and how do you handle it?
What is a skip link and why does its target need tabIndex={-1}?
Preview
Console
Nothing logged yet.Expected console output
open: true | focus: Cancel
tried to focus the page behind, focus: Cancel
open: false | focus: open