在 React Hooks 中实现 usePreviouseValue 取上次渲染的值
Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 677
Author 回答者: shfshanyue
TODO
Author 回答者: jarbinup
import { useRef } from "react";
type ShouldUpdateFunc<T> = (prev: T | undefined, next: T) => boolean;
const defalutShouldUpdate = <T>(prev?: T, next?: T) => prev !== next;
function usePrevious<T>(
state: T,
shouldUpdateFun: ShouldUpdateFunc<T> = defalutShouldUpdate,
): T | undefined {
const prev = useRef<T>();
const cur = useRef<T>();
if (shouldUpdateFun(cur.current, state)) {
prev.current = cur.current;
cur.current = state;
}
return prev.current;
}
export default usePrevious;
ahook的实现版本 很简洁