Skip to content

Instantly share code, notes, and snippets.

@Temzasse
Created June 6, 2025 10:15
Show Gist options
  • Save Temzasse/bb946d9cecdbab2f080bc5c7aae998b7 to your computer and use it in GitHub Desktop.
Save Temzasse/bb946d9cecdbab2f080bc5c7aae998b7 to your computer and use it in GitHub Desktop.
/* eslint-disable react-compiler/react-compiler */
import {
useEffect,
useRef,
type DependencyList,
type EffectCallback,
} from 'react';
import { equal } from '@wry/equality';
/**
* A custom hook that works like `useEffect` but uses deep comparison for
* dependencies. This is useful when you want to ensure that the effect only
* runs when the actual values of the dependencies change, not just their
* references.
*
* @param effect The effect callback to run.
* @param deps The dependencies array to compare deeply.
*
* Altered from: https://github.com/sandiiarov/use-deep-compare/blob/master/src/useDeepCompareMemoize.ts
*/
export function useDeepCompareEffect(
effect: EffectCallback,
deps: DependencyList
): void {
const depsRef = useRef<DependencyList>(undefined);
const signalRef = useRef<number>(0);
if (deps === undefined || !equal(deps, depsRef.current)) {
signalRef.current += 1;
}
depsRef.current = deps;
useEffect(effect, [signalRef.current]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment