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>;
}
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>;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With