import * as React from 'react' type Setter = React.Dispatch> export function usePersistedState(key: string, initialValue: T): [T, Setter] { const init = read(key) ?? initialValue const [value, setValue] = React.useState(init) React.useEffect( function () { write(key, value) }, [value], ) return [value, setValue] } function read(key: string): T | null { try { const item = window.localStorage.getItem(key) if (!item) { return null } return JSON.parse(item) } catch (err) { window.localStorage.removeItem(key) return null } } function write(key: string, value: T) { const item = JSON.stringify(value) window.localStorage.setItem(key, item) }