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
import { useState } from 'react'; export function ReorderableList({ initialItems }) { const [items, setItems] = useState(initialItems);
Drag-to-reorder lists in React
drag-and-drop
state-management
immutable-updates
Intermediate
8 steps
javascript
import { unstable_cache, revalidateTag } from 'next/cache' import { db } from '@/lib/db' export const getDashboardStats = unstable_cache(
Caching dashboard stats in Next.js
caching
cache-invalidation
tag-based-revalidation
Intermediate
8 steps
javascript
import { Component } from 'react'; import { reportError } from './services/telemetry'; export class ErrorBoundary extends Component {
How a React ErrorBoundary works
error-handling
lifecycle-methods
render-props
Intermediate
8 steps
javascript
const FOCUSABLE = [ 'a[href]', 'button:not([disabled])', 'input:not([disabled])',
How to trap keyboard focus in a dialog
accessibility
dom
event-handling
Intermediate
8 steps
javascript
function generateCalendarGrid(year, month) { const firstDay = new Date(year, month, 1); const lastDay = new Date(year, month + 1, 0); const daysInMonth = lastDay.getDate();
Building a text calendar in JavaScript
date-handling
grid-layout
modular-arithmetic
Intermediate
9 steps
javascript
function initScrollSpy() { const links = Array.from(document.querySelectorAll('.nav a[href^="#"]')); const sections = links .map((link) => document.querySelector(link.getAttribute('href')))
Building a scroll spy with IntersectionObserver
intersectionobserver
dom
event-driven
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.