Skip to content

Instantly share code, notes, and snippets.

@hellogerard
Created June 29, 2017 16:20
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 hellogerard/6fc562350e5789d581d2ad7e4b1c2fb6 to your computer and use it in GitHub Desktop.
Save hellogerard/6fc562350e5789d581d2ad7e4b1c2fb6 to your computer and use it in GitHub Desktop.
/* eslint-disable no-console */
import _ from 'lodash';
// Drop this into a component that wastes time according to Perf.printWasted()
// to find out what state/props should be preserved. Once it says "Update
// avoidable!" for {state, props}, you should be able to drop in
// React.addons.PureRenderMixin or React.PureComponent.
//
// From: http://benchling.engineering/deep-dive-react-perf-debugging/
//
// Usage:
//
// componentDidUpdate(prevProps, prevState) {
// whyDidYouUpdate.call(this, prevProps, prevState);
// }
function isRequiredUpdateObject(o) {
return Array.isArray(o) || (o && o.constructor === Object.prototype.constructor);
}
function deepDiff(o1, o2, p) {
const notify = (status) => {
console.warn('Update %s', status);
console.log('%cbefore', 'font-weight: bold', o1);
console.log('%cafter ', 'font-weight: bold', o2);
};
if (!_.isEqual(o1, o2)) {
console.group(p);
if ([o1, o2].every(_.isFunction)) {
notify('avoidable?');
} else if (![o1, o2].every(isRequiredUpdateObject)) {
notify('required.');
} else {
const keys = _.union(_.keys(o1), _.keys(o2));
for (const key of keys) {
deepDiff(o1[key], o2[key], key);
}
}
console.groupEnd();
} else if (o1 !== o2) {
console.group(p);
notify('avoidable!');
if (_.isObject(o1) && _.isObject(o2)) {
const keys = _.union(_.keys(o1), _.keys(o2));
for (const key of keys) {
deepDiff(o1[key], o2[key], key);
}
}
console.groupEnd();
}
}
function whyDidYouUpdate(prevProps, prevState) {
deepDiff({ props: prevProps, state: prevState },
{ props: this.props, state: this.state },
this.constructor.displayName);
}
export default whyDidYouUpdate;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment