Skip to content

Instantly share code, notes, and snippets.

@aswinsekar
Created August 16, 2020 13:08
Show Gist options
  • Save aswinsekar/e48c11139d3ec92e3f005faf8ea3345a to your computer and use it in GitHub Desktop.
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.
/**
* 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