import { useEffect , useState , SetStateAction , Dispatch , useCallback , } from 'react' ; import { syncStorage } from './storage' ; import { storageNamespace } from './constants' ; import deepEquals from 'fast-deep-equal' ; export const useStatePersist = < T > ( key , initialValue ? ) : [ T , Dispatch < SetStateAction < T > > ] => { const [ state , setState ] = useState ( ( ) => { try { const item = syncStorage . getItem < T > ( storageNamespace + key ) ; return item ? item : initialValue ; } catch ( error ) { console . error ( error ) ; return initialValue ; } } ) ; useEffect ( ( ) => { const unsubscribe = syncStorage . subscribe ( storageNamespace + key , ( data ) => { if ( isState ( data ) ) return ; setState ( data ) ; } ) ; return ( ) => unsubscribe ( ) ; } , [ ] ) ; const updateState = data => { try { const valueToStore = data instanceof Function ? data ( state as T ) : data ; setState ( valueToStore ) ; syncStorage . setItem ( storageNamespace + key , valueToStore ) ; } catch ( error ) { console . error ( error ) ; } } ; const isState = useCallback ( ( compareValue ) => { return deepEquals ( state , compareValue ) ; } , [ state ] ) ; return [ state as T , updateState ] ; } ;