Skip to content

Instantly share code, notes, and snippets.

@romellem
Created April 6, 2023 15:41
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 romellem/7179a97fc6c5456e3f4a3d91488ab60b to your computer and use it in GitHub Desktop.
Save romellem/7179a97fc6c5456e3f4a3d91488ab60b to your computer and use it in GitHub Desktop.
WhyDidYouUpdate react class component helper
function comparePrevPropsAndState(prevProps, prevState, logName) {
try {
const defaultLogName = `${this.constructor?.name || ''} Updated:`.trim();
const allPropsKeys = Object.keys(Object.assign({}, prevProps, this.props));
const allStateKeys = Object.keys(Object.assign({}, prevState, this.state));
const changesObj = { props: {}, state: {} };
let somethingChange = false;
for (let [keys, prev, currStore] of [
[allPropsKeys, prevProps, 'props'],
[allStateKeys, prevState, 'state'],
]) {
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
if (prev[key] !== this[currStore][key]) {
somethingChange = true;
changesObj[currStore][key] = {
from: prev[key],
to: this[currStore][key],
};
}
}
}
// If changesObj not empty then output to console
if (somethingChange) {
console.log(logName || defaultLogName, changesObj);
}
} catch (err) {
console.warning('Failed to determine render changes:', err);
}
}
class SomeComponent extends React.Component {
// ...
componentDidUpdate(prevProps, prevState) {
// You need to `.call()` the function and pass in the component's `this` as the context.
comparePrevPropsAndState.call(this, prevProps, prevState /*, "Optional log, otherwise component name will be used" */);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment