import { useState , useEffect , useCallback } from 'react' ; const isClient = typeof window !== 'undefined' ; const useLocalStorage = < T > ( key , initialValue ) : [ T , ( value : T ) => void ] => { if ( ! isClient ) { return [ initialValue , ( ) => { } ] ; } const [ state , updateState ] = useState ( ( ) : T => { try { const localStorageValue = window . localStorage . getItem ( key ) ; if ( localStorageValue === null ) { window . localStorage . setItem ( key , JSON . stringify ( initialValue ) ) ; return initialValue ; } else { return JSON . parse ( localStorageValue ) ; } } catch { return initialValue ; } } ) ; const localStorageChanged = ( e ) => { if ( e . key === key ) { updateState ( JSON . parse ( e . newValue as string ) ) ; } } ; const setState = useCallback ( ( value ) => { window . localStorage . setItem ( key , JSON . stringify ( value ) ) ; updateState ( value ) ; } , [ key , updateState ] ) ; useEffect ( ( ) => { window . addEventListener ( 'storage' , localStorageChanged ) ; return ( ) => { window . removeEventListener ( 'storage' , localStorageChanged ) ; } ; } ) ; return [ state , setState ] ; } ; export default useLocalStorage ;