Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hook Implementation causes slower count sidebyside

Why is the first functional component slower than the second functional component when they are composed side by side in a React application and you switch tabs and then go back to it after a few seconds?

Here is a sandbox so you can see it in action.

https://codesandbox.io/s/useeffect-87pm7

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

  useEffect(() => {
    const intervalId = setInterval(() => {
      setCount(count + 1);
    }, 1000);

    return () => clearInterval(intervalId);
  }, [count]);

  return <div>The count is: {count}</div>;
}
function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setCount(count => ++count);
    }, 1000);

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

  return <div>The count is: {count}</div>;
}
like image 568
Jeremy Levett Avatar asked May 03 '26 03:05

Jeremy Levett


1 Answers

The problem is that in the second useEffect you set and clear a new interval on every render, while others keep running on the same instance.

It causes a different effect on the interval when you switching tabs, therefore, the useEffect logic and the understanding of how browser tabs work causes the "bug".

Try adding logging for every clearing function in useEffect:

function SuggestedWayToUseEffectOneButItsActuallyNotWorkingCorrectly() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    const intervalId = setInterval(() => {
      setCount(count + 1);
    }, 1000);

    return () => {
      console.log('cleared 2');
      clearInterval(intervalId);
    };
  }, [count]);

  return <div>The count is: {count}</div>;
}

Edit useEffect

like image 171
Dennis Vash Avatar answered May 05 '26 09:05

Dennis Vash



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!