javascript 43 lines · 7 steps

Syncing search state with the URL hash in React

A React search box keeps its query in the URL hash, debounces the sync, and scrolls to the matching section.

Explained by highlit
1import { useState, useEffect, useRef } from 'react';
2 
3export function SectionSearch({ sections }) {
4 const [query, setQuery] = useState(() => decodeURIComponent(window.location.hash.slice(1)));
5 const debounceRef = useRef(null);
6 
7 useEffect(() => {
8 clearTimeout(debounceRef.current);
9 debounceRef.current = setTimeout(() => {
10 const next = query ? `#${encodeURIComponent(query)}` : ' ';
11 window.history.replaceState(null, '', next);
12 }, 250);
13 return () => clearTimeout(debounceRef.current);
14 }, [query]);
15 
16 useEffect(() => {
17 if (!query) return;
18 const match = sections.find((s) =>
19 s.title.toLowerCase().includes(query.toLowerCase())
20 );
21 if (!match) return;
22 const el = document.getElementById(match.id);
23 el?.scrollIntoView({ behavior: 'smooth', block: 'start' });
24 }, [query, sections]);
25 
26 useEffect(() => {
27 const onHashChange = () => {
28 setQuery(decodeURIComponent(window.location.hash.slice(1)));
29 };
30 window.addEventListener('hashchange', onHashChange);
31 return () => window.removeEventListener('hashchange', onHashChange);
32 }, []);
33 
34 return (
35 <input
36 type="search"
37 value={query}
38 onChange={(e) => setQuery(e.target.value)}
39 placeholder="Jump to section..."
40 aria-label="Search sections"
41 />
42 );
43}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Seeding state from the URL makes a component's view sharable and restorable across reloads.
  2. 2A ref holding a timer id lets you debounce side effects and cancel them cleanly on unmount.
  3. 3Listening for hashchange closes the loop so browser navigation feeds back into component state.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Syncing search state with the URL hash in React — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code