FSD Frontend System Design

Part IV — The Reach · Lesson 8.4

Focus Management

In one lineWhen the UI changes, you must decide where focus goes — the browser only gets it right on full page loads.

Where you've seen itAn SPA where navigating to page 4 leaves focus on <body>, so the next Tab starts from the logo again.

  • Time16 min
  • DiagramFocus state machine for a dialog + SPA route change
  • Chapter8 · Accessibility

Diagram

diagram
diagram
SPA ROUTE CHANGE — nothing happens unless you make it

  full page load     browser resets focus + announces the new title ✓
  SPA navigation     URL changes, DOM swaps, focus unchanged        ✗

  fix, on every route change:
    1. move focus to the <h1> (tabindex="-1") or a skip target
    2. update document.title
    3. announce via a polite live region (8.3)
diagram

How it works

  1. Save the trigger before opening any overlay, and restore focus to it on close.
  2. Trap focus inside modals — cycle Tab within the dialog and make the rest of the page inert.
  3. Never focus something the user didn't cause. Autofocus on page load and focus stealing from toasts are both hostile.
  4. On route change, move focus to the new <h1> with tabindex="-1", update the title, and announce it.
  5. On form error, focus a summary listing the problems and link each entry to its field.
js
function openDialog() {
  triggerRef.current = document.activeElement;      // remember
  dialogRef.current.showModal();                     // <dialog> traps for you
}
function closeDialog() {
  dialogRef.current.close();
  triggerRef.current?.focus();                       // restore
}

The native <dialog> element handles trapping, background inertness, and Escape for you. Prefer it over a hand-built modal.

Trade-offs

DoDon't
Restore focus to the triggerDrop focus to <body>
Trap focus in modalsTrap focus anywhere else
Focus the first field in a form dialogAutofocus on every page load
Move focus after destructive actionsLeave focus on a removed node

Interview angle

"Your SPA is accessible on first load but not after navigation. Why?"

  • Client-side routing swaps the DOM without the focus and announcement reset a real navigation performs.
  • Fix by moving focus to the new heading, updating document.title, and announcing via a polite live region.
  • The same class of bug hits deletions — focus left on a removed node falls back to <body> and the user loses their place.

Recap

  • Every UI change is a focus decision; the browser only handles full page loads.
  • Save the trigger, trap inside modals, restore on close.
  • Focusing a removed element silently sends the user back to the top.