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

useLocalStorage: Combining useState with useEffect

Build a practical custom hook that syncs state with localStorage by composing useState and useEffect together.

useLocalStorage: Combining useState with useEffect

You'll learn how to build a custom hook that automatically saves and loads state from the browser's localStorage.

The Core Idea

useLocalStorage is a practical custom hook that makes state persistent across page refreshes. It combines useState to manage the value and useEffect to sync that value with localStorage. When the component mounts, it reads from localStorage. When state changes, it writes back to localStorage.

Think of it like auto-save in a document editor: you type (change state), and the document saves automatically (writes to localStorage). When you reopen the editor (mount the component), your work is still there (reads from localStorage).

Building useLocalStorage

function useLocalStorage(key, initialValue) {
  // Read from localStorage on mount
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      return initialValue;
    }
  });

  // Write to localStorage when state changes
  useEffect(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(storedValue));
    } catch (error) {
      console.error(error);
    }
  }, [key, storedValue]);

  return [storedValue, setStoredValue];
}

Using It

function MyComponent() {
  const [name, setName] = useLocalStorage('username', '');
  
  return <input value={name} onChange={e => setName(e.target.value)} />;
}

The lazy initializer in useState prevents reading from localStorage on every render. The useEffect watches for state changes and persists them automatically.

Key Takeaway: Custom hooks like useLocalStorage compose built-in hooks to create reusable, declarative patterns—here, seamlessly syncing state with browser storage.