UNPKG

@uiw/react-native

Version:
43 lines (42 loc) 1.06 kB
import { useRef, useEffect } from 'react'; import { usePersistFn, useUpdate } from 'ahooks'; /** * 获取上一轮的 props 或 state * How to get the previous props or state? * https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state * @example * ```js * function Counter() { * const [count, setCount] = useState(0); * const prevCount = usePrevious(count); * return <h1>Now: {count}, before: {prevCount}</h1>; * } * ``` */ export function usePrevious(value) { const ref = useRef(); useEffect(() => { ref.current = value; }); return ref.current; } export function usePropsValue(options) { const { value, defaultValue, onChange } = options; const update = useUpdate(); const stateRef = useRef(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]; }