Created
May 28, 2025 17:57
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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