i’ve an effect function set up and was wondering if the cleanup function was really necessary in this scenario.
this is a basic component which just increments the counter every second.
since this useEffect will only run on the initial mount, only one setinterval function will be set up and that will keep functioning as the counter. since the useEffect will never run again, the cleanup function will never even be fired. correct me if i’m wrong.
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(c => c + 1);
}, 1000);
return () => clearInterval(id);
},[]);
return <h1>{count}</h1>;
}
another question:
what if there is no second arg in the useEffect. since the state changes, the useEffect will now run as many times. so a new setInterval function is created each time? so it would make sense to include a cleanup function as without it, several setInterval functions would keep running together? Am i right in this regard?
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(c => c + 1);
}, 1000);
return () => clearInterval(id);
}); // no dependency array.
return <h1>{count}</h1>;
}
>Solution :
For the first question:
- The
clearIntervalwill be called not only when the useEffect is called again, but while component unmounting, as well. - If you omit the
clearIntervalcall, the timer will still send messages after the component is unmounted and you will get warnings in console. In most practical scenarios this is a question of performance and code purity, but one can imagine when this could cause issues.
For the second question:
Yes.
Find more here
Understanding React’s useEffect cleanup function