How to capture time spent by a user on a page in react




To capture the time spent by a user on a page in a React application, you can use the useEffect hook to set up a timer when the component is mounted, and clear the timer when the component is unmounted. Here's an example code snippet:

import { useState, useEffect } from 'react';

function MyComponent() {
  const [timeSpent, setTimeSpent] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      setTimeSpent(timeSpent => timeSpent + 1);
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  return (
    <div>
      <p>You've spent {timeSpent} seconds on this page</p>
    </div>
  );
}

In this example, we use the useState hook to keep track of the time spent, and the useEffect hook with an empty dependency array ([]) to set up a timer when the component is mounted.

The setInterval function is used to run a callback function every second, which updates the timeSpent state by incrementing it by 1.

Finally, we use the return statement in the useEffect hook to clear the timer when the component is unmounted, using the clearInterval function.

With this code in place, the MyComponent will display the number of seconds the user has spent on the page, and this value will update every second until the component is unmounted.