Need help to understand in useEffect, if I don’t put counter and timerCheck in useEffect dependency then what it will effect here.
And if I put timerCheck dependency in useEffect then counter increasing 100 time faster
Also how can i run this code without any error or warning
code in codesandbox
JavaScript
x
28
28
1
const [counter, setCounter] = useState(0);
2
const [startcounter, setStartcounter] = useState(false);
3
const [timerCheck, setTimerCheck] = useState(0);
4
5
useEffect(() => {
6
let intervalStart = null;
7
if (startcounter) {
8
intervalStart = setInterval(() => {
9
setCounter((prevState) => (prevState += 1));
10
}, 1000);
11
setTimerCheck(intervalStart);
12
} else {
13
clearInterval(timerCheck);
14
}
15
16
return () => {
17
if (counter !== 0) clearInterval(timerCheck);
18
};
19
}, [startcounter]);
20
21
const handleStartButton = () => {
22
setStartcounter(true);
23
};
24
25
const handleStopButton = () => {
26
setStartcounter(false);
27
};
28
Advertisement
Answer
Try not to declare unnecessary states. timerCheck
state is redundant.
- You want to start an interval that increases counter by one every second.
- When user stops the stopwatch , you want the interval to be cleared, so it would stop increasing the
timer
.
So your only dependancy in useEffect
would be whether your stopwatch is running or not. And the only thing that matters to you, is when startCounter
is ture
. You start an interval when it is true and clear the interval in its cleanup.
JavaScript
1
16
16
1
useEffect(() => {
2
let intervalStart = null;
3
4
if (!startcounter) {
5
return () => {};
6
}
7
8
intervalStart = setInterval(() => {
9
setCounter((prevState) => (prevState += 1));
10
}, 1000);
11
12
return () => {
13
clearInterval(intervalStart);
14
};
15
}, [startcounter]);
16
Here is the codesandbox
But you do not really need useEffect
for this. IMO it would be a much better code without using useEffect
.