Use Deep Compare - React hooks, except using deep comparison on the inputs, not reference equality. Read about Hooks feature.
npm i use-deep-compare
yarn add use-deep-compare
pnpm add use-deep-compare
bun add use-deep-compare
import React from "react";
import { useDeepCompareEffect } from "use-deep-compare";
function App({ object, array }) {
useDeepCompareEffect(() => {
// do something significant here
return () => {
// return to clean up that significant thing
};
}, [object, array]);
return <div>{/* render significant thing */}</div>;
}
import React from "react";
import { useDeepCompareCallback } from "use-deep-compare";
function App({ object, array }) {
const callback = useDeepCompareCallback(() => {
// do something significant here
}, [object, array]);
return <div>{/* render significant thing */}</div>;
}
import React from "react";
import { useDeepCompareLayoutEffect } from "use-deep-compare";
function App({ object, array }) {
useDeepCompareLayoutEffect(() => {
// perform layout effects
}, [object, array]);
return <div>{/* render component */}</div>;
}
import React from "react";
import { useDeepCompareMemo } from "use-deep-compare";
function App({ object, array }) {
const memoized = useDeepCompareMemo(() => {
// do something significant here
}, [object, array]);
return <div>{/* render significant thing */}</div>;
}
import React from "react";
import { useDeepCompareImperativeHandle } from "use-deep-compare";
function App({ object, array }) {
const ref = React.useRef();
useDeepCompareImperativeHandle(ref, () => ({
// create imperative methods
}), [object, array]);
return <div ref={ref}>{/* render component */}</div>;
}
To receive eslint warnings about missing array dependencies, just like for standard useEffect
, useCallback
, useMemo
, ... hooks - extend you eslint config as follows:
{
"rules": {
// ...
"react-hooks/exhaustive-deps": ["warn", {
"additionalHooks": "(useDeepCompareEffect|useDeepCompareCallback|useDeepCompareMemo|useDeepCompareImperativeHandle|useDeepCompareLayoutEffect)"
}]
}
}
- Inspired by use-deep-compare-effect.