Created
December 16, 2019 16:41
-
-
Save lynndylanhurley/f52db5d48935d1ab6020673ac6578dd4 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, useEffect } from 'react'; | |
// stolen from: | |
// https://usehooks.com/useWhyDidYouUpdate/ | |
export default function useRenderDebugger(name, props) { | |
// Get a mutable ref object where we can store props ... | |
// ... for comparison next time this hook runs. | |
const previousProps = useRef(); | |
useEffect(() => { | |
if (previousProps.current) { | |
// Get all keys from previous and current props | |
const allKeys = Object.keys({ ...previousProps.current, ...props }); | |
// Use this object to keep track of changed props | |
const changesObj = {}; | |
// Iterate through keys | |
allKeys.forEach(key => { | |
// If previous is different from current | |
if (previousProps.current[key] !== props[key]) { | |
// Add to changesObj | |
changesObj[key] = { | |
from: previousProps.current[key], | |
to: props[key], | |
}; | |
} | |
}); | |
// If changesObj not empty then output to console | |
if (Object.keys(changesObj).length) { | |
console.log('[why-did-you-update]', name, changesObj); | |
} | |
} | |
// Finally update previousProps with current props for next hook call | |
previousProps.current = props; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment