Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading