Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import { useCallback, useEffect, useState } from "react"; export function useLocalStorageState<T>( defaultValue: T, key: string, ): [T, (value: T | ((prev: T) => T)) => void] { const [value, setValue] = useState<T>(() => { try { const stored = localStorage.getItem(key); Iif (stored !== null) { return JSON.parse(stored) as T; } } catch {} return defaultValue; }); useEffect(() => { try { localStorage.setItem(key, JSON.stringify(value)); } catch {} }, [key, value]); const set: typeof setValue = useCallback((update) => { setValue((prev) => typeof update === "function" ? (update as (prev: T) => T)(prev) : update, ); }, []); return [value, set]; } |