Course contentsShow
← React
Lesson 966 of 2,39625. Custom HooksFree lesson

useLocalStorage Example

Build a hook that syncs state with localStorage, handling serialization and storage events automatically.

useLocalStorage Example

You'll learn how to build a custom hook that automatically persists state to localStorage and keeps it in sync across browser tabs.

The Problem We're Solving

When you need state that survives page refreshes, you typically write repetitive code: read from localStorage on mount, write on every update, handle JSON parsing/stringifying, and deal with browser inconsistencies. This pattern appears in almost every app (theme preferences, draft forms, user settings), so it's perfect for a custom hook.

Building useLocalStorage

This hook combines useState and useEffect to create state that automatically syncs with localStorage:

function useLocalStorage(key, initialValue) {
  // Read from localStorage on initial render
  const [value, setValue] = useState(() => {
    const stored = localStorage.getItem(key);
    return stored ? JSON.parse(stored) : initialValue;
  });

  // Write to localStorage whenever value changes
  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

Using It

function UserPreferences() {
  const [theme, setTheme] = useLocalStorage('theme', 'light');
  const [fontSize, setFontSize] = useLocalStorage('fontSize', 16);

  return (
    <div>
      <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
        Toggle Theme (currently: {theme})
      </button>
      <button onClick={() => setFontSize(fontSize + 2)}>
        Increase Font ({fontSize}px)
      </button>
    </div>
  );
}

The interface looks identical to useState, but now your data persists automatically. Refresh the page—your theme and font size remain!

Why This Works

The lazy initializer in useState runs only once on mount, reading from localStorage. The effect writes back on every change. The hook handles all serialization for you.

Key Takeaway: Custom hooks like useLocalStorage encapsulate complex patterns (state + side effects + serialization) into a simple, reusable interface that feels like a built-in React feature.