deep-compare-hooks
v1.0.0
Published
Wrap React hooks to deep-compare dependency arrays and avoid unnecessary reruns
Maintainers
Readme
deep-compare-hooks
Wrap React hooks (useEffect, useMemo, useCallback) so dependency arrays are compared deeply instead of by reference.
React compares hook dependencies with Object.is, so a new object or array reference on every render will retrigger the hook even when the contents are unchanged. This library deep-compares those dependencies and passes a stable reference to React when the values are equal.
Install
npm install deep-compare-hooksreact is a peer dependency (18+).
Usage
Import the wrapper with any name you like:
import useDeepCompare from "deep-compare-hooks";
import { useCallback, useEffect, useMemo } from "react";
useDeepCompare(useEffect, () => {
// runs only when deps change deeply
}, [{ a: 1 }]);
const memoizedFn = useDeepCompare(useCallback, () => {}, [{ a: 1 }]);
const memoizedValue = useDeepCompare(useMemo, () => compute(), [{ a: 1 }]);Pass the React hook as the first argument, your callback or factory as the second, and your dependency array as the third. Types are inferred from the hook you pass in.
When to use
Use this when:
- A dependency is an object or array that may be recreated with the same contents
- You cannot easily memoize the value upstream with
useMemo/useCallback - You need deep equality rather than reference equality
Prefer native React hooks when dependencies are already stable primitives or memoized values.
Development
npm install
npm run typecheck
npm test
npm run buildLicense
ISC
