Skip to content

Instantly share code, notes, and snippets.

@christophermark
Last active August 22, 2020 13:37
Show Gist options
  • Save christophermark/2fcf53f55d2ccd74b29900a047e42305 to your computer and use it in GitHub Desktop.
Save christophermark/2fcf53f55d2ccd74b29900a047e42305 to your computer and use it in GitHub Desktop.
Log the diffs between props in a react component
componentDidUpdate(prevProps) {
console.log("Render update diff:");
const now = Object.entries(this.props);
const added = now.filter(([key, val]) => {
if (prevProps[key] === undefined && val !== undefined) return true;
if (prevProps[key] !== val) {
console.log(`${key}
+ ${JSON.stringify(val)}
- ${JSON.stringify(prevProps[key])}`);
}
return false;
});
added.forEach(([key, val]) =>
console.log(`${key}
+ ${JSON.stringify(val)}
- undefined`)
);
}
@christophermark
Copy link
Author

christophermark commented Aug 22, 2020

For just the prop names, not their whole object

  componentDidUpdate(prevProps) {
    const now = Object.entries(this.props);
    const added = now.filter(([key, val]) => {
      if (prevProps[key] === undefined && val !== undefined) return true;
      if (prevProps[key] !== val) {
        console.count(`${key}`);
      }
      return false;
    });
    added.forEach(([key, val]) => console.count(`${key}`));
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment