跳到主要内容

useDeepCompareEffect

修改后的 useEffect ,对其依赖项使用深度比较而不是引用相等

Usage

实时编辑器

function Demo() {
  const [count, setCount] = useState(0);
  const effectCountRef = useRef(0);
  const deepCompareCountRef = useRef(0);

  useEffect(() => {
    effectCountRef.current += 1;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [{}]);

  useDeepCompareEffect(() => {
    deepCompareCountRef.current += 1;
    return () => {
      // do something
    };
  }, [{}]);

  return (
    <div>
      <p>effectCount: {effectCountRef.current}</p>
      <p>deepCompareCount: {deepCompareCountRef.current}</p>
      <p>
        <button type="button" onClick={() => setCount(c => c + 1)}>
          reRender
        </button>
      </p>
    </div>
  );
};

结果
Loading...

API

useDeepCompareEffect

Returns

void

Arguments

参数名描述类型默认值
effect副作用函数React.EffectCallback (必填)-
deps依赖列表React.DependencyList (必填)-