import { useRef , useEffect } from 'react' ; import { usePersistFn , useUpdate } from 'ahooks' ; example export function usePrevious < T > ( value ) { const ref = useRef < T > ( ) ; useEffect ( ( ) => { ref . current = value ; } ) ; return ref . current ; } type Options < T > = { value ? : T ; defaultValue : T ; onChange ? : ( v : T ) => void ; } ; export function usePropsValue < T > ( options ) { const { value , defaultValue , onChange } = options ; const update = useUpdate ( ) ; const stateRef = useRef < T > ( value !== undefined ? value : defaultValue ) ; if ( value !== undefined ) { stateRef . current = value ; } const setState = usePersistFn ( ( v ) => { if ( value === undefined ) { stateRef . current = v ; update ( ) ; } onChange ?. ( v ) ; } ) ; return [ stateRef . current , setState ] as const ; }