import { useState, useEffect, Dispatch, SetStateAction } from 'react' function isDefined (storedValue: string | null): boolean { return storedValue !== null && storedValue !== 'undefined'; } export function useLocalStorageState( key: string, initialValue: T ): [T, Dispatch>] { const [state, setState] = useState(() => { const storedValue = localStorage.getItem(key) return isDefined(storedValue) ? (JSON.parse(storedValue!) as T) : initialValue }) useEffect(() => { localStorage.setItem(key, JSON.stringify(state)) }, [key, state]) return [state, setState] };