import { useRef , useCallback , useState , MutableRefObject } from 'react' ; import { useIsomorphicLayoutEffect } from './env' ; import { State } from '../types' ; type StateKeys = keyof State < any , any > ; type StateDeps = Record < StateKeys , boolean > ; /**
 * An implementation of state with dependency-tracking.
 */ export const useStateWithDeps = < Data , Error , S = State < Data , Error > > ( state , unmountedRef ) : [ MutableRefObject < S > , Record < StateKeys , boolean > , ( payload : S ) => void ] => { const rerender = useState < Record < string , unknown > > ( { } ) [ 1 ] ; const stateRef = useRef ( state ) ; const stateDependenciesRef = useRef < StateDeps > ( { data : false , error : false , isValidating : false } ) ; param payload example const setState = useCallback ( ( payload ) => { let shouldRerender = false ; const currentState = stateRef . current ; for ( const _ in payload ) { const k = _ as keyof S & StateKeys ; if ( currentState [ k ] !== payload [ k ] ) { currentState [ k ] = payload [ k ] ; if ( stateDependenciesRef . current [ k ] ) { shouldRerender = true ; } } } if ( shouldRerender && ! unmountedRef . current ) { rerender ( { } ) ; } } , [ ] ) ; useIsomorphicLayoutEffect ( ( ) => { stateRef . current = state ; } ) ; return [ stateRef , stateDependenciesRef . current , setState ] ; } ;