Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure how long a React component is rendered

In my React app, I have a component that is shown only when a user hovers over another element. I wanted to measure how long this component is displayed using the useLayoutEffect where I'm returning a cleanup that measures the difference in time between the cleanup function call and the initial function call. I would assume that since the cleanup function is called after the initial useLayoutEffect function that the differences in time I compute would always be positive but this doesn't seem to be the case. Sometimes this value is negative. What am I missing?

My component is something like the following:

const MyComponent = () => {

  useLayoutEffect(() => {
    const startTime = new Date();
    return () => {
       const endTime = new Date();
       const timeRendered = endTime.getMilliseconds() - startTime.getMilliseconds();
       console.log(timeRendered); // Expect this to be a positive number
    }
  }, []);

  return <>{/* stuff */}</>;
}
like image 659
FettFrank Avatar asked Feb 28 '26 06:02

FettFrank


1 Answers

getMilliseconds returns only the milliseconds part of a Date, which is 0 to 999; it's like doing % 1000 on their timestamps. Try subtracting the dates instead, to get their timestamp differences.

const MyComponent = () => {

  useLayoutEffect(() => {
    const startTime = new Date();
    return () => {
       const endTime = new Date();
       const timeRendered = endTime - startTime;
       console.log(timeRendered); // Expect this to be a positive number
    }
  }, []);

  return <>{/* stuff */}</>;
}
like image 93
CertainPerformance Avatar answered Mar 01 '26 23:03

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!