Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save theslantedroom/34443290fc5edf24107033cc5c424846 to your computer and use it in GitHub Desktop.
Save theslantedroom/34443290fc5edf24107033cc5c424846 to your computer and use it in GitHub Desktop.
An example of how to log what dependency array item changed to trigger a useEffect
import { useEffect, useRef, useState } from 'react';
export const useDebugEffectDepArrayChanges = () => {
const [s1, setS1] = useState(false);
const [s2, setS2] = useState(false);
const [s3, setS3] = useState(false);
const prevDepsRef = useRef<{
s1: boolean;
s2: boolean;
s3: boolean;
}>();
/**
* An example of how to log what dependency array item changed to trigger a useEffect
*/
useEffect(() => {
const deps = {
s1,
s2,
s3,
};
if (prevDepsRef.current) {
Object.entries(deps).forEach(([key, value]) => {
const prevValue = prevDepsRef.current?.[key as keyof typeof deps];
if (prevValue !== value) {
console.log(`Dependency changed: ${key}`, {
previous: prevValue,
current: value,
});
}
});
}
prevDepsRef.current = deps;
}, [s1, s2, s3]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment