Reputation: 337
I am building a small game with React and I am set to include a countdown timer on it.
There are many tutorials (including one in React's official documentation) on how to create a timer or countdown timer with React. All of them however use the componentDidMount
and componentWillUnmount
lifecycle methods to set and respectively clear the interval.
This works fine, but the timer starts counting the moment the component mounts. I d like to have a timer that starts counting onClick.
What are the appropriate lifecycle methods to achieve such a behavior? I ve already tried componentWillUpdate
and componentDidUpdate
but to no effect.
My first thought was to use a gameOn state property in order to activate the timer only when game is on (ie the start button has been pressed) but this did not work because (I guess) I am setting gameOn to true, long after the component didMount.
I have also tried to move these two methods along with appropriate state ({secondsElapsed: 0}) on the Timer component, since Timer is a seperate component that communicates with its parent through props. This too had no luck.
Finally I tried setting this.interval = null;
on my constructor function but this had no difference on the way the Timer is functioning.
I am thinking that the root of the issue is the lifecycle methods because these control when the setInterval and clearInterval will be called. So my question is this:
Which other combo of lifecycle methods should I use to achieve the behavior I am after?
Any well versed suggestions will be appreciated.
Bonus points if you can explain in clear terms on why and when should I declare this.interval = null;
on my constructor function.
For an example of what I have so far, really basically look at the "A Stateful Component"
Upvotes: 1
Views: 3018
Reputation: 852
componentWillUnmount() {
clearInterval(this.interval); // Always clean up before unmounting
}
render(){
<div>
<button
onClick={() => { this.interval = setInterval(() => {
// Do something here e.g. increment the time
// NOTE: `this` keyword here refers to the component itself
}, 1000); }}>
Start
</button>
</div>
}
Upvotes: 5