Created
March 21, 2023 12:20
-
-
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
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 { 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