javascript
32 lines · 6 steps
A React hook backed by the URL hash
useHashState mirrors a piece of state into the URL fragment so it survives reloads and stays shareable.
Explained by
highlit
1function useHashState(key, defaultValue) {
2 const parse = () => {
3 const params = new URLSearchParams(window.location.hash.slice(1));
4 return params.has(key) ? params.get(key) : defaultValue;
5 };
6
7 const [value, setValue] = React.useState(parse);
8
9 React.useEffect(() => {
10 const onHashChange = () => setValue(parse());
11 window.addEventListener('hashchange', onHashChange);
12 return () => window.removeEventListener('hashchange', onHashChange);
13 }, [key]);
14
15 const update = React.useCallback(
16 (next) => {
17 const params = new URLSearchParams(window.location.hash.slice(1));
18 if (next === defaultValue || next == null || next === '') {
19 params.delete(key);
20 } else {
21 params.set(key, next);
22 }
23 const hash = params.toString();
24 const url = hash ? `#${hash}` : window.location.pathname + window.location.search;
25 window.history.replaceState(null, '', url);
26 setValue(next ?? defaultValue);
27 },
28 [key, defaultValue]
29 );
30
31 return [value, update];
32}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1The URL hash can act as a persistent, shareable store for lightweight UI state.
- 2Syncing external state into React means listening for its change events and cleaning the listener up.
- 3Removing a key when its value is the default keeps URLs clean rather than littered with defaults.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
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/a-react-hook-backed-by-the-url-hash-explained-javascript-3c85/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.