import {useState, useEffect} from 'react' const init = {defined: false} export default function useLocalStorage(key, defaultValue) { const [state, setState] = useState(init) // Load from localstorage on first render or if key changes useEffect(() => { const stored = window.localStorage.getItem(key) try { if(!stored) throw new Error('No stored value') setState(JSON.parse(stored)) } catch { setState(defaultValue) } }, [key]) // Persist to localstorage when state changes useEffect(() => { if(state === init) { return } window.localStorage.setItem(key, JSON.stringify(state)) }, [state]) if(state === init) return [defaultValue, setState] return [state, setState]; }