Skip to content

Instantly share code, notes, and snippets.

@tomasswood
Last active May 20, 2019 06:19
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 tomasswood/d96d6b69d31eaf2f13fe2a0526560d5d to your computer and use it in GitHub Desktop.
Save tomasswood/d96d6b69d31eaf2f13fe2a0526560d5d to your computer and use it in GitHub Desktop.
Log mapStateToProps changes and see what properties are actually changing and causing re-renders
/**
* Log a table in the console of all provided props and whether they have strict equality
*
* @param oldProps
* @param newProps
* @constructor
*/
export const PropDiff = (oldProps, newProps) => {
let match = {};
Object.keys(oldProps).forEach((oldPropKey) => {
const oldValue = oldProps[oldPropKey];
const newValue = newProps[oldPropKey];
match[oldPropKey] = oldValue === newValue;
});
console.table({ old: oldProps, new: newProps, match: match }, Object.keys(oldProps));
};
/**
* Create a cache of the previous object returned from mapStateToProps and log how many times each individual prop changes over time
*
* Usage: Wrap the returned object in your mapStateToProps function with this function
*
* @param mapStateToProps
* @returns {*}
*/
const logMapStateToPropsChanges = (mapStateToProps) => {
window.cachedState = window.cachedState || {};
console.group('mapStateToPropsCalled');
console.count('Total Times Called');
Object.keys(window.cachedState).forEach((stateKey) => {
if (window.cachedState[stateKey] !== mapStateToProps[stateKey]) {
console.count(stateKey);
}
});
PropDiff(window.cachedState, mapStateToProps);
console.groupEnd();
window.cachedState = mapStateToProps;
return mapStateToProps;
};
export default logMapStateToPropsChanges;
const mapStateToProps = (state) => {
const propOne = selector(state);
const propTwo = anotherSelector(state);
return logMapStateToPropsChanges({
propOne,
propTwo,
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment