高级前端
react
【Q659】在 React Hooks 中实现 usePreviouseValue 取上次渲染的值

在 React Hooks 中实现 usePreviouseValue 取上次渲染的值

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 677 (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

TODO

Author 回答者: jarbinup (opens in a new tab)

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的实现版本 很简洁