I want to benchmark rendering of a React component so that I could make incremental improvements.
I came up with this prototype for use with react v18:
import {
useEffect,
} from 'react';
import {
createRoot,
} from 'react-dom';
import {
JsonView,
} from '../components/JsonView';
const render = (root) => {
return new Promise((resolve) => {
root.render(<div ref={() => {
resolve(undefined);
}}
>
<JsonView
activePath={null}
entries={{foo: 'bar'}}
expanded
highlights={[]}
onActivePathChange={() => {}}
/>
</div>);
});
};
const TestPage = () => {
useEffect(() => {
const sandbox = document.createElement('div');
document.body.appendChild(sandbox);
const root = createRoot(sandbox);
(async () => {
const startTime = Date.now();
const runTime = 1_000;
let renderCount = 0;
while (Date.now() - startTime < runTime) {
await render(root);
renderCount++;
}
console.log('done', renderCount);
})();
return () => {
document.body.removeChild(sandbox);
};
}, []);
return <div />;
};
export default TestPage;
JsonView is the component that I want to benchmark.ref is used to identify when div is created.startTime / runTime are used to limit test suite run time.This works well – I am getting consistent benchmark outputs and making changes to the component shows performance improvement / degradation.
However, I was wondering if this is the right way to benchmark a React component or if I should be using another mechanism?