QuickSnip
← Back to browse

useLocalStorage hook

Persist React state to localStorage and keep it in sync.

TypeScript16 linesUpdated Jul 17, 2026
Edit
TypeScript
import { useEffect, useState } from "react";

export function useLocalStorage(key, initial) {
  const [value, setValue] = useState(() => {
    try {
      const raw = window.localStorage.getItem(key);
      return raw ? JSON.parse(raw) : initial;
    } catch {
      return initial;
    }
  });
  useEffect(() => {
    window.localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);
  return [value, setValue];
}