| import { useEffect, useState } from "react"; | |
| export function useLocalStorage<T>(key: string, initial: T): [T, (v: T) => void] { | |
| const [value, setValue] = useState<T>(initial); | |
| useEffect(() => { | |
| try { | |
| const stored = localStorage.getItem(key); | |
| if (stored !== null) { | |
| setValue(JSON.parse(stored)); | |
| } | |
| } catch (_) {} | |
| // eslint-disable-next-line react-hooks/exhaustive-deps | |
| }, []); | |
| useEffect(() => { | |
| try { | |
| localStorage.setItem(key, JSON.stringify(value)); | |
| } catch (_) {} | |
| }, [key, value]); | |
| return [value, setValue]; | |
| } | |