Created
August 16, 2020 13:08
-
-
Save aswinsekar/e48c11139d3ec92e3f005faf8ea3345a to your computer and use it in GitHub Desktop.
This hook will not return anything. It will log into console, the changed props, from the previous render.
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
/** | |
* usage | |
* | |
* const MyComp = (props) => { | |
useTraceUpdate(props) | |
return <span />; | |
}; | |
*/ | |
import { useRef, useEffect } from "react"; | |
function useTraceUpdate (props) { | |
const propRef = useRef(props); | |
useEffect(() => { | |
const changedProps = Object.entries(props).reduce((lookup, [key, value]) => { | |
if (propRef.current[key] !== value) { | |
lookup[key] = [propRef.current[key], value]; | |
} | |
return lookup; | |
}, {}); | |
if (Object.keys(changedProps).length > 0) { | |
if (console.table) { | |
console.table(changedProps); | |
} else { | |
console.log("Changed Props: ", changedProps); | |
} | |
} | |
propRef.current = props; | |
}); | |
} | |
export { useTraceUpdate }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment