I'm reading through the React documentation. The section on controlled components explains that because form elements (say, an <input>) maintain their own internal state, you should use controlled components that allow the React state to be the "single source of truth", e.g.:
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
In the example above, each time I enter a character into the input field, the handleChange method is called, which updates the React state to account for the new character, by setting state's value member to event.target.value. This implies that the character I just typed had already been added to the DOM, and then the React state was updated by retrieving it from the value property of the DOM input element. This change in React state would then cause the render() method to be called again, which would then re-render the component based on the new state.
Does this not mean that each new character is rendered twice, once by the HTML itself when you type it into the <input> tag, and then again by React after the state has been updated? Or am I misunderstanding something?
Any clarification would be much appreciated. Thanks!