I am trying to create an automatic counter in react which stops at 60. Here is my code:
import React, { Component } from "react";
class Profile extends Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
}
tick() {
if (this.state.seconds < 60) {
this.setState(prevState => ({
seconds: prevState.seconds + 1
}));
}
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 100);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return <div>Seconds: {this.state.seconds}</div>;
}
}
export default Profile;
It stops at 60 but I am worried that the component will continue to ask for the tick function again and again. I am not sure if it is the best practice or if there is a better way to do that. Thank you for your help.