Daily-Question icon indicating copy to clipboard operation
Daily-Question copied to clipboard

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

Open shfshanyue opened this issue 4 years ago • 2 comments

shfshanyue avatar Jul 19 '21 12:07 shfshanyue

TODO

shfshanyue avatar Jul 20 '21 02:07 shfshanyue

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

jarbinup avatar Apr 30 '22 03:04 jarbinup