ReactEasy
Custom hook example?
A classic example is useLocalStorage(key, initialValue): it works like useState but persists the value in localStorage, reads it lazily on first render, handles JSON errors, and stays in sync across browser tabs through the storage event.
What makes it a good custom hook
- Familiar API: returns
[value, setValue]likeuseState, including updater functions. - Lazy initialization: reads storage only once.
- Safe parsing: falls back to the initial value on invalid JSON or when storage is unavailable (private mode, server rendering).
- Cross-tab sync: listens for
storageevents and updates when another tab changes the key. - Cleanup: removes the listener on unmount.
Variations
useSessionStoragewith the same shape.- A version built on
useSyncExternalStorefor multiple components on the same page sharing one key. - Libraries:
usehooks-tsprovides a well-testeduseLocalStorage.
Server rendering note
localStorage does not exist on the server. In SSR frameworks, render the initial value on the server and read storage after hydration (or use useSyncExternalStore with a server snapshot) to avoid hydration mismatches.
Code example
tsx
1import { useCallback, useEffect, useState } from "react";23export function useLocalStorage<T>(key: string, initialValue: T) {4 const [value, setValue] = useState<T>(() => {5 try {6 const raw = window.localStorage.getItem(key);7 return raw !== null ? (JSON.parse(raw) as T) : initialValue;8 } catch {9 return initialValue; // invalid JSON or storage blocked10 }11 });1213 const set = useCallback(14 (next: T | ((prev: T) => T)) => {15 setValue((prev) => {16 const resolved = typeof next === "function" ? (next as (p: T) => T)(prev) : next;17 try {18 window.localStorage.setItem(key, JSON.stringify(resolved));19 } catch {}20 return resolved;21 });22 },23 [key]24 );2526 useEffect(() => {27 const onStorage = (e: StorageEvent) => {28 if (e.key === key) setValue(e.newValue ? JSON.parse(e.newValue) : initialValue); // other tabs29 };30 window.addEventListener("storage", onStorage);31 return () => window.removeEventListener("storage", onStorage);32 }, [key, initialValue]);3334 return [value, set] as const;35}3637// const [theme, setTheme] = useLocalStorage<"light" | "dark">("theme", "light");
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.