Created
April 6, 2023 15:41
-
-
Save romellem/7179a97fc6c5456e3f4a3d91488ab60b to your computer and use it in GitHub Desktop.
WhyDidYouUpdate react class component helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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