import { useCallback, useSyncExternalStore, useRef } from "react"; // Store for managing localStorage state const localStorageStore = (() => { const listeners = new Map void>>(); function subscribe(key: string, callback: () => void) { if (!listeners.has(key)) { listeners.set(key, new Set()); } listeners.get(key)!.add(callback); // Listen for storage events from other tabs/windows const handleStorageChange = (e: StorageEvent) => { if (e.key === key && e.storageArea === localStorage) { listeners.get(key)?.forEach((listener) => listener()); } }; if (typeof window !== "undefined") { window.addEventListener("storage", handleStorageChange); } return () => { listeners.get(key)?.delete(callback); if (listeners.get(key)?.size === 0) { listeners.delete(key); } if (typeof window !== "undefined") { window.removeEventListener("storage", handleStorageChange); } }; } function notifyListeners(key: string) { listeners.get(key)?.forEach((listener) => listener()); } return { subscribe, notifyListeners }; })(); export function useLocalStorage( key: string, initialValue: T, ): [T, (value: T | ((val: T) => T)) => void] { // Use refs to store stable references const keyRef = useRef(key); const initialValueRef = useRef(initialValue); // Update refs when props change keyRef.current = key; initialValueRef.current = initialValue; const subscribe = useCallback( (callback: () => void) => localStorageStore.subscribe(keyRef.current, callback), [], ); const getSnapshot = useCallback((): T => { if (typeof window === "undefined") { return initialValueRef.current; } try { const item = window.localStorage.getItem(keyRef.current); if (item === null) return initialValueRef.current; // Handle different data types if (typeof initialValueRef.current === "string") { return item as T; } else if (typeof initialValueRef.current === "number") { return (parseFloat(item) || initialValueRef.current) as T; } else if (typeof initialValueRef.current === "boolean") { return (item === "true") as T; } else { // For objects and arrays, parse JSON return JSON.parse(item); } } catch (error) { console.warn(`Error reading localStorage key "${keyRef.current}":`, error); return initialValueRef.current; } }, []); const getServerSnapshot = useCallback((): T => { return initialValueRef.current; }, []); const storedValue = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); const setValue = useCallback( (value: T | ((val: T) => T)) => { try { // Get current value for functional updates const currentValue = getSnapshot(); // Allow value to be a function for functional updates const valueToStore = value instanceof Function ? value(currentValue) : value; // Save to localStorage only on client if (typeof window !== "undefined") { let stringValue: string; if (typeof valueToStore === "string") { stringValue = valueToStore; } else if (typeof valueToStore === "number" || typeof valueToStore === "boolean") { stringValue = valueToStore.toString(); } else { stringValue = JSON.stringify(valueToStore); } window.localStorage.setItem(keyRef.current, stringValue); // Notify all listeners for this key localStorageStore.notifyListeners(keyRef.current); } } catch (error) { console.warn(`Error setting localStorage key "${keyRef.current}":`, error); } }, [getSnapshot], ); return [storedValue, setValue]; }