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

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1Wrapping browser-storage reads and writes in try/catch keeps a hook resilient to disabled storage or quota limits.
  2. 2Passing a function initializer to useState defers the read until first render, avoiding work on every render.
  3. 3Listening for the storage event lets independent tabs stay in sync with a single source of truth.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How a useLocalStorage hook syncs state in React — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code