Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to avoid setInterval from triggering multiple times is to clear the interval before starting a new one. This can be achieved by assigning the interval to a variable and calling the clearInterval() function with that variable as a parameter before starting a new interval.

Additionally, it is important to ensure that the component is not re-rendered unnecessarily. To do this, we can use React's useMemo hook to memoize the expensive computations and only recompute them when the dependencies change.

For example, consider the following code snippet:

import { useState, useEffect, useMemo } from "react";

function MyComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setCount((prevCount) => prevCount + 1); // update count every second
    }, 1000);

    return () => clearInterval(intervalId); // clear interval on unmount
  }, []);

  const expensiveComputation = useMemo(() => {
    // compute some expensive value
    return count * 2;
  }, [count]);

  return <div>{expensiveComputation}</div>;
}

In this example, we use the useEffect hook to start and clear the interval. We also use useMemo to memoize the expensive computation and only recompute it when the count changes. This ensures that the component is not re-rendered unnecessarily and that the setInterval function is cleared before starting a new one.