React

useLocalStorage Hook

7/25/2025
5 min read

This hook synchronizes a piece of state with the browser’s local storage, allowing data to persist across page reloads. It’s essential for features like saving user preferences or form drafts.


import { useState, useEffect } from 'react';

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

  useEffect(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(storedValue));
    } catch (error) {
      console.error(error);
    }
  }, [key, storedValue]);

  return [storedValue, setStoredValue];
}

// Usage example:
// const [theme, setTheme] = useLocalStorage('theme', 'light');