javascript
49 lines · 8 steps
How a useLocalStorage hook syncs state in React
A custom React hook that mirrors component state to localStorage and keeps it in sync across tabs.
Explained by
highlit
1import { useCallback, useEffect, useState } from 'react';
2
3export function useLocalStorage(key, initialValue) {
4 const readValue = useCallback(() => {
5 try {
6 const item = window.localStorage.getItem(key);
7 return item ? JSON.parse(item) : initialValue;
8 } catch {
9 return initialValue;
10 }
11 }, [key, initialValue]);
12
13 const [storedValue, setStoredValue] = useState(readValue);
14
15 const setValue = useCallback(
16 (value) => {
17 setStoredValue((prev) => {
18 const next = value instanceof Function ? value(prev) : value;
19 try {
20 window.localStorage.setItem(key, JSON.stringify(next));
21 } catch {
22 /* quota exceeded or unavailable */
23 }
24 return next;
25 });
26 },
27 [key]
28 );
29
30 useEffect(() => {
31 const handleStorage = (event) => {
32 if (event.key !== key || event.storageArea !== window.localStorage) return;
33 try {
34 setStoredValue(event.newValue ? JSON.parse(event.newValue) : initialValue);
35 } catch {
36 setStoredValue(initialValue);
37 }
38 };
39
40 window.addEventListener('storage', handleStorage);
41 return () => window.removeEventListener('storage', handleStorage);
42 }, [key, initialValue]);
43
44 useEffect(() => {
45 setStoredValue(readValue());
46 }, [readValue]);
47
48 return [storedValue, setValue];
49}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Wrapping browser-storage reads and writes in try/catch keeps a hook resilient to disabled storage or quota limits.
- 2Passing a function initializer to useState defers the read until first render, avoiding work on every render.
- 3Listening for the storage event lets independent tabs stay in sync with a single source of truth.
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
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
javascript
function collapseConsecutiveLogs(lines, { keyFn = (l) => l.message } = {}) { const groups = []; for (const line of lines) {
Collapsing consecutive log lines in JavaScript
grouping
run-length-encoding
data-transformation
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/how-a-uselocalstorage-hook-syncs-state-in-react-explained-javascript-ed52/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.