import { useState, useCallback } from 'react'; export function useLocalStorage(key: string, initialValue: T): [T, (value: T | ((val: T) => T)) => void] { const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { return initialValue; } }); const setValue = useCallback((value: T | ((val: T) => T)) => { try { const valueToStore = value instanceof Function ? value(storedValue) : value; setStoredValue(valueToStore); window.localStorage.setItem(key, JSON.stringify(valueToStore)); } catch (error) { console.log(error); } }, [key, storedValue]); return [storedValue, setValue]; }