Why My Variable "intervalId" Is Not Getting The Value Updated When I Call The Function "StopTimer" Function?
Here is my simple code: import React, { useState } from 'react'; import './App.css'; function App() { const [time, setTime] = useState(0); var intervalId; function startTim
Solution 1:
Because intervalId
is not the same variable that was in scope when startTimer
was invoked. It will be undefined
in all the subsequent renders. ( caused when time
change state )
In React, if you want to "keep a value" across the life cycle of a component, you can use a ref
for it:
// ....
var intervalId = React.useRef();
// ....
intervalId.current = setInterval(() => {
// ...
clearInterval(intervalId.current);
Solution 2:
Since the App
is invoked everytime you change the state (setTime
), you get a new, fresh value of the local variable.
One of options is to include the variable in your state.
function App() {
var [time, setTime] = useState(0);
var [intervalId, setIntervalId] = useState(0);
function startTimer() {
setIntervalId(intervalId => setInterval(() => {
setTime(time => time + 1);
}, 1000));
}
function stopTimer() {
clearInterval(intervalId);
}
return (
<div className="App">
<div>{time}</div>
<div>
<button onClick={startTimer}>Start time</button>
<button onClick={stopTimer}>Stop time</button>
</div>
</div>
);
}
Post a Comment for "Why My Variable "intervalId" Is Not Getting The Value Updated When I Call The Function "StopTimer" Function?"