Why does this code does not give maximum update depth exceeded while we are using setState inside the render method.
class Test extends Component {
state = {
name: ""
};
handleChange = e => {
this.setState({
name: e.target.value
});
};
render() {
return (
<div>
<input type="text" name="name" onChange={this.handleChange} />
</div>
);
}
}
this.handleChange is only called when change happens on the input field. Maximum update depth exceeded only happens if you call the function like this: onChange{this.handleChange()} because it automatically rerender (calling setState) itself and going inside an infinite loop. You should read about onchange property for more information: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onchange