import { useEffect } from 'react' ; import { useStore , Action , Dispatch , getState } from 'stook' ; function getLocalValue ( key ) { if ( typeof window === 'undefined' ) return null ; const localValue = window . localStorage . getItem ( key ) ; try { return JSON . parse ( localValue ) ; } catch { return localValue ; } } export function useLocalStorage < S = any > ( key , initialState ? ) { const [ state , setState ] = useStore < any > ( key , ! ! initialState || getLocalValue ( key ) ) ; const setItem = ( newValue ) => { setState ( newValue ) ; const storageValue = typeof newValue === 'object' ? JSON . stringify ( newValue ) : newValue ; window . localStorage . setItem ( key , storageValue ) ; } ; useEffect ( ( ) => { const localValue = window . localStorage . getItem ( key ) ; if ( typeof initialState !== 'undefined' && initialState !== localValue ) { const storageValue = typeof initialState === 'object' ? JSON . stringify ( initialState ) : initialState ; window . localStorage . setItem ( key , storageValue as any ) ; } } , [ ] ) ; try { const objectValue = JSON . parse ( state ) ; return [ objectValue , setItem ] ; } catch ( error ) { return [ state , setItem ] ; } } export function getLocalStorage < S = any > ( key ) { const state = getState < S > ( key ) ; return state || getLocalValue ( key ) ; }