javascript
30 lines · 6 steps
Managing focus on route change in React
A wrapper that moves keyboard focus to the page heading and updates the document title every time the route changes.
Explained by
highlit
1import { useEffect, useRef } from "react";
2import { useLocation } from "react-router-dom";
3
4export function RouteFocus({ title, children }) {
5 const headingRef = useRef(null);
6 const location = useLocation();
7
8 useEffect(() => {
9 const heading = headingRef.current;
10 if (!heading) return;
11
12 const timer = window.setTimeout(() => {
13 heading.focus();
14 heading.scrollIntoView({ block: "start" });
15 }, 0);
16
17 document.title = title ? `${title} \u2013 Acme` : "Acme";
18
19 return () => window.clearTimeout(timer);
20 }, [location.pathname, title]);
21
22 return (
23 <main>
24 <h1 ref={headingRef} tabIndex={-1} className="page-title">
25 {title}
26 </h1>
27 {children}
28 </main>
29 );
30}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Moving focus to a heading on navigation keeps screen-reader and keyboard users oriented after client-side route changes.
- 2A tabIndex of -1 makes an element programmatically focusable without inserting it into the tab order.
- 3Cleaning up timers in the effect's return prevents stale callbacks from firing after unmount or a rapid re-navigation.
Related explainers
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
8 steps
go
package handlers import ( "net/http"
Serving embedded static meta files in Gin
embedding
static assets
http caching
Intermediate
6 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
javascript
import { useState, useEffect, useCallback } from 'react'; function getColumnCount(width) { if (width < 640) return 1;
A responsive column hook in React
custom-hooks
debouncing
responsive-design
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/managing-focus-on-route-change-in-react-explained-javascript-d6c4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.