shfshanyue / Daily-Question

互联网大厂内推及大厂面经整理,并且每天一道面试题推送。每天五分钟,半年大厂中
https://q.shanyue.tech
4.92k stars 508 forks source link

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

Open shfshanyue opened 3 years ago

shfshanyue commented 3 years ago

TODO

jarbinup commented 2 years ago
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的实现版本 很简洁