I am getting a problem in making a countdown timer which will start on clicking on start button and it will stop onClicking on the stop button. I have made that thing on javascript but when I came to reactJs, I am getting unable. I am providing all the codes. And please check what is the problem.
JavaScript
x
30
30
1
import React, { useState } from "react";
2
import "./styles.css";
3
4
const App = () => {
5
const [data, setData] = useState(0);
6
let interval;
7
return (
8
<>
9
<div id="Message"> {data} </div>
10
<button
11
onClick={() => {
12
interval = setInterval(() => {
13
setData(data + 1);
14
}, 1000);
15
}}
16
>
17
Start
18
</button>
19
<button
20
onClick={() => {
21
clearInterval(interval);
22
}}
23
>
24
End
25
</button>
26
</>
27
);
28
};
29
export default App;
30
Advertisement
Answer
Issues
- The timer/interval reference is redeclared each render cycle, so you can never clear it once anything causes the component to rerender.
- You’ve a stale enclosure of the
data
state value in the interval callback.
Solution
- Use a React ref to hold the interval reference.
- Use a functional state update to correctly update the
data
counter.
Code
JavaScript
1
27
27
1
const App = () => {
2
const [data, setData] = useState(0);
3
const intervalRef = useRef();
4
5
return (
6
<>
7
<div id="Message"> {data} </div>
8
<button
9
onClick={() => {
10
intervalRef.current = setInterval(() => {
11
setData(c => c + 1);
12
}, 1000);
13
}}
14
>
15
Start
16
</button>
17
<button
18
onClick={() => {
19
clearInterval(intervalRef.current);
20
}}
21
>
22
End
23
</button>
24
</>
25
);
26
};
27