import { Dispatch, SetStateAction, useEffect, useState } from "react"; type SetValue = Dispatch>; export function useLocalStorage( key: string, initialValue: T ): [T, SetValue] { const [storedValue, setStoredValue] = useState(initialValue); useEffect(() => { const item = window.localStorage.getItem(key); if (item) { setStoredValue(parseJSON(item)); } }, [key]); const setValue: SetValue = (value) => { const newValue = value instanceof Function ? value(storedValue) : value; window.localStorage.setItem(key, JSON.stringify(newValue)); setStoredValue(newValue); }; return [storedValue, setValue]; } function parseJSON(value: string): T { return value === "undefined" ? undefined : JSON.parse(value); }