Rreact.wiki
React Snippets

React hook for persistent state in localStorage

Hookshooklocal-storagestate-persistencereacttypescript

A custom React hook that synchronizes component state with browser localStorage, supporting functional updates and error resilience.

TSX
import { useState, useEffect } from 'react';
 
function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T | ((prevValue: T) => T)) => void] {
  // State to store our value
  // Pass initial state function to useState so logic is only executed once
  const [storedValue, setStoredValue] = useState<T>(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.error(error);
      return initialValue;
    }
  });
 
  // Return a wrapped version of useState's setter function that 
  // persists the new value to localStorage
  const setValue = (value: T | ((prevValue: T) => T)) => {
    try {
      // Allow value to be a function so we have same API as useState
      const valueToStore = value instanceof Function ? value(storedValue) : value;
      setStoredValue(valueToStore);
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      console.error(error);
    }
  };
 
  return [storedValue, setValue];
}
 
export default useLocalStorage;

This hook lets you persist React component state in localStorage with the same ergonomic API as useState. It safely parses stored JSON on init and handles errors during read/write. To use it, call const [value, setValue] = useLocalStorage('my-key', defaultValue) — then use value and setValue just like useState. Note: values must be JSON-serializable; non-serializable types (e.g., functions, Date objects without string conversion) will cause silent failures or unexpected behavior. The hook does not auto-sync across tabs — for that, listen to storage events separately.