# 在 React Hooks 中实现 usePreviouseValue 取上次渲染的值
Issue
欢迎在 Gtihub Issue 中回答此问题: Issue 677 (opens new window)
Author
TODO
Author
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 的实现版本 很简洁