import { useState, useEffect } from 'react'; export function useLocalStorage(key: string, initialValue: T) { // Get from localStorage then // parse stored JSON or if none return initialValue const readValue = () => { if (typeof window === 'undefined') { return initialValue; } try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { console.warn(`Error reading localStorage key “${key}”:`, error); return initialValue; } }; const [storedValue, setStoredValue] = useState(readValue); // Return a wrapped version of useState's setter function that ... // ... persists the new value to localStorage. const setValue = (value: T) => { if (typeof window == 'undefined') { console.warn( `Tried setting localStorage key “${key}” even though environment is not a client`, ); } try { const newValue = value instanceof Function ? value(storedValue) : value; // Save to localStorage window.localStorage.setItem(key, JSON.stringify(newValue)); // Save state setStoredValue(newValue); // We dispatch a custom event so every useLocalStorage hook are notified window.dispatchEvent(new Event('local-storage')); } catch (error) { console.warn(`Error setting localStorage key “${key}”:`, error); } }; const removeValue = () => { try { window.localStorage.removeItem(key); setStoredValue(null); } catch (error) { console.warn(`Error removing localStorage key “${key}”:`, error); } }; const checkIfKeyExists = (): boolean => { try { return window.localStorage.getItem(key) !== null; } catch (error) { console.warn(`Error checking localStorage key “${key}”:`, error); return false; } }; useEffect(() => { setStoredValue(readValue()); }, []); useEffect(() => { const handleStorageChange = () => { setStoredValue(readValue()); }; // this only works for other documents, not the current one window.addEventListener('storage', handleStorageChange); // this is a custom event, triggered in writeValueToLocalStorage window.addEventListener('local-storage', handleStorageChange); return () => { window.removeEventListener('storage', handleStorageChange); window.removeEventListener('local-storage', handleStorageChange); }; }, []); return [storedValue, setValue, removeValue, checkIfKeyExists]; }