Skip to content

Instantly share code, notes, and snippets.

@szhu
Created January 14, 2024 02:41
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 szhu/c37600f846489b4356856b95f642a846 to your computer and use it in GitHub Desktop.
Save szhu/c37600f846489b4356856b95f642a846 to your computer and use it in GitHub Desktop.
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