Reputation: 8604
I'm learning how to use <form>
's in React and most examples I've seen use a combination of state
and onChange
to keep track of your form's inputs:
class Form extends React.Component {
handleChange(event) {
this.setState({
inputvalue: event.target.value
})
}
render() {
return (
<form onSubmit={this.handleSubmit.bind(this)}>
<label>Name</label>
<input type="text" value={this.state.inputvalue} onChange={this.handleChange.bind(this)}/>
<input type="submit" value="Submit"/>
</form>
);
}
}
However, say I have numerous <input>
's and even some <textarea>
's which might change quite often. In that case each one of them would call the onChange
method each time they are updated and the component would re-render on every key press.
Seeing as how people can type pretty fast, could this be an area for concern?
Upvotes: 2
Views: 1388
Reputation: 95
In a small testing I discovered that React successfully performs a shallow compare in the state and changes in the DOM in just the components that need a re-render. In Chrome I enabled the highlights (Paint Flashing) of the areas that were repainted by React in the DOM.
See the Paint Flashing in action.
In my example note that onChange
will run on every keystroke to update the React state, the displayed value will update as the user types (based on the React Docs https://reactjs.org/docs/forms.html#controlled-components).
Also you can see my code here: https://codepen.io/anon/pen/KxjJRp
class Application extends React.Component {
state = {
value1: "",
value2: "",
value3: "",
value4: ""
}
onChange = ({target: {value, name}}) => {
this.setState({
[name]: value
})
}
render() {
const { state: { value1, value2, value3, value4 } } = this
return (
<div>
<label>Value 1</label>
<input type="text" value={value1} name="value1" onChange={this.onChange}/>
<label>Value 2</label>
<input type="text" value={value2} name="value2" onChange={this.onChange}/>
<label>Value 3</label>
<input type="text" value={value3} name="value3" onChange={this.onChange}/>
<label>Value 4</label>
<input type="text" value={value4} name="value4" onChange={this.onChange}/>
</div>
)
}
}
Upvotes: 3
Reputation: 230
I am not totally sure of the best way to handle this but I could see an implementation of setting an onblur method to handle updating state. onChange would be constantly updating but this might not be the worst thing as it likely will not re-render the page with every keystroke.
Upvotes: 0