Created
January 14, 2024 02:41
-
-
Save szhu/c37600f846489b4356856b95f642a846 to your computer and use it in GitHub Desktop.
This file contains 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 { useRef } from "react"; | |
/** | |
* Use this hook to quickly answer the question: Why did my useEffect or useMemo | |
* callback run again? | |
* | |
* Usage: | |
* | |
* // If you have this code... | |
* useEffect(() => { | |
* ... | |
* }, [a, b, c]) | |
* | |
* // ... then add this code right above or below it: | |
* const keysChanged = useDebugWhichKeysChanged({ a, b, c }) | |
* if (keysChanged.length > 0) { | |
* console.log('These keys changed:', keysChanged) | |
* } | |
* | |
*/ | |
export function useDebugWhichKeysChanged(items: Record<string, any>) { | |
const prevItemsRef = useRef<Record<string, any>>({}); | |
const keys = Object.keys(items); | |
const changed = keys.filter( | |
(key) => items[key] !== prevItemsRef.current[key] | |
); | |
prevItemsRef.current = items; | |
return changed; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment