I've been developing applications with react for a while. I use both the official site of react and examples from other sources. However, I have a question. Why should I setState in the onChange of each input element? This renders the page unnecessary rendering. Let me explain myself with a simple example.
Let's have an input textbox. If the user presses submit after entering the values, we want to show that value on the screen. I can do this example in 2 kinds. But I don't know which one to choose. I will be grateful if you could help me.
In Example 1, the page is rendered only when I click the submit button.
However, in example 2, the situation is different. The page is rendered for each value I enter in the textbox. And when I press submit button, the page is rendered.
When I look on the Internet, it is usually shown as in example 1. It gives the same result in 2 examples. But which one should I prefer?
Example 1 :
class App extends React.Component {
state = {
value: ''
}
handleSubmit = e => {
e.preventDefault();
this.setState({ value: this.textInput.value})
};
render() {
return (
<div>
<h1>React Ref - Callback Ref</h1>
<h3>Value: {this.state.value}</h3>
<form onSubmit={this.handleSubmit}>
<input type="text" ref={e => this.textInput = e} />
<button>Submit</button>
</form>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
Example 2 :
class App extends React.Component {
state = {
value: ''
}
handleSubmit = e => {
e.preventDefault();
this.setState({ value: e.target.value})
};
onChange = e => {
this.setState({ value: e.target.value})
};
render() {
return (
<div>
<h1>React Ref - Callback Ref</h1>
<h3>Value: {this.state.value}</h3>
<form onSubmit={this.handleSubmit}>
<input type="text" onChange={this.onChange} />
<button>Submit</button>
</form>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));