Blog>
Snippets

Tracking Component Render Performance with `mark` and `measure`

Demonstrate how to use window.performance.mark() and window.performance.measure() to monitor the performance of component rendering.
// Define a higher-order component that tracks the performance of another component
function withPerformanceMonitoring(WrappedComponent) {
    return class extends React.Component {

        // Start tracking when the component gets mounted
        componentDidMount() {
            window.performance.mark(`${WrappedComponent.name}-mount-start`);
        }

        // Complete the tracking when the component updates
        componentDidUpdate() {
            window.performance.mark(`${WrappedComponent.name}-update-end`);
            window.performance.measure(
                `${WrappedComponent.name} update time`,
                `${WrappedComponent.name}-mount-start`,
                `${WrappedComponent.name}-update-end`
            );
            console.log(window.performance.getEntriesByType('measure'));
        }

        // Reset the tracking on unmount to avoid memory leaks
        componentWillUnmount() {
            window.performance.clearMarks(`${WrappedComponent.name}-mount-start`);
            window.performance.clearMarks(`${WrappedComponent.name}-update-end`);
            window.performance.clearMeasures(`${WrappedComponent.name} update time`);
        }

        render() {
            return <WrappedComponent {...this.props} />;
        }
    };
}
This piece of code defines a higher-order component (HOC) that wraps another component to track its mounting and updating performance using the Performance API. It uses `performance.mark()` to record timestamps for the start of mount and the end of updates, and `performance.measure()` to calculate the duration between these marks. Finally, it logs the measures to the console and clears them to avoid memory leaks when the component is unmounted.