import { useState } from 'react'; /** * A custom React hook to synchronize state with localStorage. * @param {string} key - The key for the localStorage item. * @param {any} initialValue - The initial value if no item exists in localStorage. * @returns {[any, Function]} A tuple containing the stored value and a setter function. */ function useLocalStorage(key, initialValue) { const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { console.error("Error reading from localStorage:", error); return initialValue; } }); const setValue = (value) => { try { const valueToStore = value instanceof Function ? value(storedValue) : value; setStoredValue(valueToStore); window.localStorage.setItem(key, JSON.stringify(valueToStore)); } catch (error) { console.error("Error writing to localStorage:", error); } }; return [storedValue, setValue]; }