Last active
October 9, 2019 17:29
-
-
Save mikelfcosta/1ed7dd5f923be8eaea761e0312676bb0 to your computer and use it in GitHub Desktop.
A basic log object and React 16.9 Profiler callback function to evaluate the number and speed of mounts and updates of a React component. Useful for testing tiny differences in components like if the usage of useMemo or useCallback hooks are improving or worsening the Component.
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
import React, {Profiler} from 'react'; | |
import callback from './profiler'; | |
function anyComponent() { | |
return ( | |
<Profiler id="any-component" onRender={callback}> | |
<div>Some Component</div> | |
</Profiler> | |
); | |
} |
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 log = { | |
mountCount: 0, | |
updateCount: 0, | |
averageMountTime: 0, | |
averageUpdateTime: 0, | |
totalMountTime: 0, | |
totalUpdateTime: 0, | |
}; | |
export function callback( | |
id, // the "id" prop of the Profiler tree that has just committed | |
phase, // either "mount" (if the tree just mounted) or "update" (if it re-rendered) | |
actualDuration, // time spent rendering the committed update | |
baseDuration, // estimated time to render the entire subtree without memoization | |
startTime, // when React began rendering this update | |
commitTime, // when React committed this update | |
interactions, // the Set of interactions belonging to this update | |
) { | |
if (phase === 'mount') { | |
log.mountCount += 1; | |
log.totalMountTime += actualDuration; | |
log.averageMountTime = log.totalMountTime / log.mountCount; | |
} | |
if (phase === 'update') { | |
log.updateCount += 1; | |
log.totalUpdateTime += actualDuration; | |
log.averageUpdateTime = log.totalUpdateTime / log.updateCount; | |
} | |
console.info(log); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment