Skip to content

Instantly share code, notes, and snippets.

@httnn
Created June 24, 2019 07:47
Show Gist options
  • Save httnn/feb4af86fc678d9c3f7aa7ba18dc2863 to your computer and use it in GitHub Desktop.
Save httnn/feb4af86fc678d9c3f7aa7ba18dc2863 to your computer and use it in GitHub Desktop.
const updateReason = fn =>
function(prevProps, prevState) {
const isEqual = (a, b) => {
if (a === null || b === null || a === undefined || b === undefined) {
return a === b;
} else if (a.constructor === Object && b.constructor === Object) {
const keysA = Object.keys(a).sort();
const keysB = Object.keys(b).sort();
if (keysA.join(',') === keysB.join(',')) {
return keysA.every(key => isEqual(a[key], b[key]));
}
} else if (a.constructor === Array && b.constructor === Array) {
if (a.length === b.length) {
return a.every((item, i) => isEqual(item, b[i]));
}
} else if (a.constructor === b.constructor) {
return a === b;
}
return false;
};
const logChange = (prevValue: Object, nextValue: Object, label: string) => {
const changes = Object.keys(prevValue)
.filter(k => prevValue[k] !== nextValue[k])
.map(key => ({
key,
prev: prevValue[key],
next: nextValue[key],
areEqual: isEqual(prevValue[key], nextValue[key])
}));
const equalChanges = changes.filter(c => c.areEqual).length;
if (changes.length) {
console.groupCollapsed(
`${label}: ${
changes.length
} changed of which ${equalChanges} are equal`
);
changes.forEach(({ prev, next, key, areEqual }) => {
console.log(`${key}:`, prev, areEqual ? '==' : '!=', next);
});
console.groupEnd();
}
};
console.warn('Component re-rendered!');
logChange(prevProps, this.props, 'props');
if (prevState) {
logChange(prevState, this.state, 'state');
}
if (fn) {
fn(prevProps, prevState);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment