Skip to content

Instantly share code, notes, and snippets.

@4lun
Created March 21, 2023 12:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 4lun/f5787cc95951cdd9ad38f655cda78e3a to your computer and use it in GitHub Desktop.
Save 4lun/f5787cc95951cdd9ad38f655cda78e3a to your computer and use it in GitHub Desktop.
Simple useEffect debug hook for figuring out which dependencies have changed in React
import { DependencyList, EffectCallback, useEffect, useRef } from 'react';
const useEffectDebug = (
effect: EffectCallback,
deps: DependencyList,
label?: string,
) => {
const previous = useRef<DependencyList>();
useEffect(() => {
const changedDepIndexes: number[] = [];
if (previous.current) {
deps.forEach((dep, i) => {
if (dep !== previous.current?.[i]) {
changedDepIndexes.push(i);
}
});
}
if (changedDepIndexes.length > 0) {
const { text, background } = textContrastStyle();
const style = `color: ${text}; background: ${background}`;
const prefix = `useEffectDebug${label ? `[${label}]` : ''}:`;
const changedDeps = changedDepIndexes.reduce(
(acc, i) => ({
...acc,
[i]: { previous: previous.current?.[i], current: deps[i] },
}),
{},
);
console.log(
`%c${prefix} ${changedDepIndexes.length}/${
deps.length
} dependencies changed [${changedDepIndexes.join(',')}]`,
`font-weight: bold; ${style}`,
changedDeps,
);
}
previous.current = deps;
effect();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
};
function textContrastStyle() {
const hue = Math.floor(Math.random() * 360);
const text = `hsl(${hue}, 100%, 10%)`;
const background = `hsl(${(hue + 180) % 360}, 100%, 90%)`;
return { text, background };
}
export default useEffectDebug;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment