Reputation: 17
I am incrementing a counter by setState() of React using a setInterval method. But for every intervals the application is updating multiple times.
import React, { Component } from 'react';
export default class Arrival extends Component {
state = {
count: 0,
limitTo: 6
}
render() {
try {
setInterval(() => {
this.setState({
limitTo: this.state.limitTo + 6
})
console.log(this.state)
}, 5000);
} catch(err) {
console.log(err)
}
return()
}
}
In the first 5 seconds, the state is getting updated once.
In the next 5 seconds, the state is getting updated 2 times.
In the next 5 seconds, the state is getting updated 4 times. and so on...
I want the state to only get updated once every 5 seconds.
Upvotes: 0
Views: 210
Reputation: 3091
setInterval()
is called in render()
method. This means that:
setInterval()
is called in render()
method. Timers ticking: 2.To solve this, move setInterval
to componentDidMount()
as recommended by another answer to ensure the timer is started once only, not on each render
.
Upvotes: 1
Reputation: 6556
when the state update, the component will be also updated and re-render, hence the setInterval
should not be inside render
method. You can do this instead:
class Arrival extends Component {
state = {
count: 0,
limitTo: 6
};
interval = 0;
componentDidMount() {
try {
this.interval = setInterval(() => {
this.setState({
limitTo: this.state.limitTo + 6
});
console.log(this.state);
}, 5000);
} catch (err) {
console.log(err);
}
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return <div />;
}
}
Note: reminded by @FrankerZ, you should also clean up the interval when the component unmounts, otherwise the clock will keep ticking ;)
Upvotes: 1