Last active
June 30, 2022 11:29
-
-
Save mackankowski/53843a02399f4dbac5b972624c24dc6b to your computer and use it in GitHub Desktop.
Debug React component's props changes (performance analysis)
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
/* eslint-disable no-console */ | |
// goal: debug props changes (performance analysis) | |
// alternative for https://github.com/welldone-software/why-did-you-render | |
// usage: memo(someComponent, arePropsEqualDebug(someComponent.name) | |
// read more: https://reactjs.org/docs/react-api.html#reactmemo | |
// tip: use console.count() for getting a number of renders | |
function areEqualShallow(a: any, b: any) { | |
for(var key in a) { | |
if(a[key] !== b[key]) { | |
return false; | |
} | |
} | |
return true; | |
} | |
export const arePropsEqual = | |
(componentName: string) => (prev: any, next: any) => { | |
// console.log(areEqualShallow({a: {}}, {a: {}})) return false | |
let arePropsEqual = true; | |
Object.keys(prev).forEach((key: any) => { | |
// FIXME | |
console.log(prev[key]); | |
console.log(next[key]) | |
console.log(areEqualShallow(prev[key], next[key])) // return true | |
arePropsEqual = areEqualShallow(prev[key], next[key]); | |
if (!arePropsEqual) { | |
console.group(`%c ${componentName}`, 'color: royalblue'); | |
console.group( | |
`%c ${key} %c props aren't equal!`, | |
'color: skyblue', | |
'color: gold', | |
); | |
console.info(`previous:`, prev[key]); | |
console.info(`next:`, next[key]); | |
console.groupEnd(); | |
console.groupEnd(); | |
} | |
}) | |
return arePropsEqual; | |
} | |
// export const arePropsEqualDebug = | |
// (componentName: string) => (prev: any, next: any) => { | |
// let arePropsEqual = true; | |
// Object.keys(prev).forEach((key: any) => { | |
// if (prev[key] !== next[key]) { | |
// arePropsEqual = false | |
// console.group(`%c ${componentName}`, 'color: royalblue'); | |
// console.group( | |
// `%c ${key} %c props aren't equal!`, | |
// 'color: skyblue', | |
// 'color: gold', | |
// ); | |
// console.info(`previous:`, prev[key]); | |
// console.info(`next:`, next[key]); | |
// console.groupEnd(); | |
// console.groupEnd(); | |
// } | |
// }); | |
// return arePropsEqual; | |
// }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment