Home > Software engineering >  Measure how long a React component is rendered
Measure how long a React component is rendered

Time:06-30

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 */}</>;
}

CodePudding user response:

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 */}</>;
}
  • Related