Skip to content

Instantly share code, notes, and snippets.

@ryanjduffy
Last active January 30, 2023 08:43
Show Gist options
  • Save ryanjduffy/b93be228b00acbba0633ed90071ee00a to your computer and use it in GitHub Desktop.
Save ryanjduffy/b93be228b00acbba0633ed90071ee00a to your computer and use it in GitHub Desktop.
Log React State Changes
import React from 'react';
const original = React.Component.prototype.setState;
const logState = function (type, current, updated) {
console.log(type.displayName || type.name || 'Component', 'updating', current, 'with', updated);
}
const logger = function (partialState, callback) {
const type = this._reactInternalInstance._currentElement.type;
if (typeof partialState === 'function') {
const partialStateCallback = partialState;
partialState = function (state, props, context) {
const updated = partialStateCallback(state, props, context);
logState(type, state, updated);
}
} else if (partialState) {
logState(type, this.state, partialState);
}
original.call(this, partialState, callback);
};
function hijack () {
React.Component.prototype.setState = logger;
}
function restore () {
React.Component.prototype.setState = original;
}
export {
hijack,
restore
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment