Last active
May 20, 2019 06:19
-
-
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
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
/** | |
* 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; |
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
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