I begin using React so i tried to make an little incrementer to test my skills and i get this problem: I get more render than expected. i should have 1 by one incrementation but i get 2 instead. I can't see where is the error in my code because i think it's ok. Can you explain me ?
I use create-react-app and there is my App.js code
import "./App.css";
import { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
value: 0,
step: 1,
timer: null,
};
}
componentDidMount() {
this.play();
}
componentWillUnmount() {
window.clearInterval(this.state.timer);
}
increment = () => {
console.log('lance');
this.setState((state) => {
return {
value: state.value + state.step,
};
});
};
play = () => {
this.setState({
timer: window.setInterval(this.increment, 1000),
});
};
pause = () => {
window.clearInterval(this.state.timer);
this.setState({
timer: null,
});
};
btnToggle = () => {
this.state.timer ? this.pause() : this.play();
};
btnLabel = () => (this.state.timer ? "Pause" : "Play");
btnClassName = () => `btn btn-${this.state.timer ? "primary" : "secondary"}`;
handleInputChange = (e) => {
console.log("Not Parsed :", e.target.value);
console.log("Parsed :", parseInt(e.target.value));
this.setState({ step: parseInt(e.target.value) });
this.pause();
this.play();
};
render() {
console.log("render");
return (
<div className="container mt-2">
<h1 className="h1">Incrementer</h1>
<div className="row">
<div className=" form-group mb-3">
<span className="number">Value : {this.state.value}</span>
<input
value={this.state.step}
onChange={this.handleInputChange}
className="form-control"
type="text"
/>
</div>
<button
type="button"
className={this.btnClassName()}
onClick={this.btnToggle}
>
{this.btnLabel()}
</button>
</div>
</div>
);
}
}
export default App;