// Created on savesnippets.com ยท https://savesnippets.com/KvuCSUAcQj3lKz import { useEffect, useState } from 'react'; export function useLocalStorage(key: string, initial: T): [T, (v: T) => void] { const [value, setValue] = useState(() => { if (typeof window === 'undefined') return initial; try { const raw = window.localStorage.getItem(key); return raw !== null ? (JSON.parse(raw) as T) : initial; } catch { return initial; } }); useEffect(() => { try { window.localStorage.setItem(key, JSON.stringify(value)); } catch {} }, [key, value]); // Sync across tabs useEffect(() => { const onStorage = (e: StorageEvent) => { if (e.key === key && e.newValue !== null) { try { setValue(JSON.parse(e.newValue) as T); } catch {} } }; window.addEventListener('storage', onStorage); return () => window.removeEventListener('storage', onStorage); }, [key]); return [value, setValue]; }