I have a timer using setInterval()
in a React component and I\'m unsure what the best practices are in order to start and stop this interval in respect to using
Using React Hooks useState
and useEffect
you can do the following:
const [timer, setTimer] = useState(1);
useEffect(() => {
const timerId = setInterval(() => setTimer(timer + 1), 1000);
return () => clearInterval(timerId);
});
I think the biggest flaw here is that you're using state
to store your interval. While technically possible, I see no reason why you would actually want to do that.
Instead, just use a local variable to your component:
startTimer(){
if(!this.timerId){
this.timerId = setInterval(()=>{
//your function
}, 1000);
}
}
stopTimer(){
clearInterval(this.timerId);
}
So I don't think you need to use the state
at all here for your timer. You have some other general questions in your post though that are related to state
, and I'll try to answer those below. Just bear in mind that they are irrelevant in solving your particular issue.
What have they've done to circumvent asynchronous issues with setState()
?
You can use a callback to execute code after the state
has been set. There's a section of the official docs about this; here's what it says:
The second parameter is an optional callback function that will be executed once setState is completed and the component is re-rendered.
setState(nextState, callback);
Which lifecycle methods would be best for this type of situation?
The same section of the doc as above continues:
Generally we recommend using componentDidUpdate() for such logic instead.
If you have multiple setState
in your function, and you want to execute specific code after a specific event, I think you're fine using the callback. For more general purposes use the life-cycle method above.