Skip to main content

useDeepCompareEffect

A modified useEffect hook that is using deep comparison on its dependencies instead of reference equality

Usage

Live Editor

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>
  );
};

Result
Loading...

API

useDeepCompareEffect

Returns

void

Arguments

ArgumentDescriptionTypeDefaultValue
effecteffect functionReact.EffectCallback (Required)-
depsdep listReact.DependencyList (Required)-