import { Dispatch , SetStateAction , useEffect , useState } from 'react' ; type SetValue < T > = Dispatch < SetStateAction < T > > ; function usePersistedState < T > ( key , defaultValue ) { const [ value , setValue ] = useState ( ( ) => { const persistedValue = window . localStorage . getItem ( key ) ; if ( persistedValue === null ) { return defaultValue ; } try { return JSON . parse ( persistedValue ) as T ; } catch { return defaultValue ; } } ) ; useEffect ( ( ) => { const item = JSON . stringify ( value ) ; window . localStorage . setItem ( key , item ) ; } , [ key , value ] ) ; return [ value , setValue ] ; } export default usePersistedState ;