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] like useState, 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 storage events and updates when another tab changes the key.
  • Cleanup: removes the listener on unmount.

Variations

  • useSessionStorage with the same shape.
  • A version built on useSyncExternalStore for multiple components on the same page sharing one key.
  • Libraries: usehooks-ts provides a well-tested useLocalStorage.

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";
2
3export 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 blocked
10 }
11 });
12
13 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 );
25
26 useEffect(() => {
27 const onStorage = (e: StorageEvent) => {
28 if (e.key === key) setValue(e.newValue ? JSON.parse(e.newValue) : initialValue); // other tabs
29 };
30 window.addEventListener("storage", onStorage);
31 return () => window.removeEventListener("storage", onStorage);
32 }, [key, initialValue]);
33
34 return [value, set] as const;
35}
36
37// 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.

Open in study app