React - updating the input "value"

Hey guys i wanna ask a question. So i’m watching a tutorial on react and i have the following code, the thing is i dont understand why why we have to update the “value” of the input with basically the value that it already has xD I placed a comment in the code to help you understand which line im talking about. I mean, why do we have to do that? I hope my question is clear :slight_smile:

class SearchBar extends React.Component {
    state = { term: '' };

    render() {
        return (
            <div className="ui segment">
                <form className="ui form">
                    <div className="field">
                        <label>Image Search</label>
                        <input
                         type="text"
//check the line bellow
                         value={this.state.term}
                          onChange={e =>
                            this.setState({ term: e.target.value})
                          } />
                    </div>
                </form>
            </div>
        );
    }
}

In programming, there is a practice called “Single source of truth” (of state in your case). Basically, this line makes sure that in any given moment, the value of input you see in the view is the same as term, and not the one the built-in state of input element has.

*Technically, it’s especially necessary with React because while built-in state of HTML elements is updating synchronously, React state is updated asynchronously, meaning there are moments when states are different.

So if my understanding is correct. Its not wrong to not update the “value” , but we do it just in case(in react)?

The value will be updated by itself using internal state of input - you can test it by removing the line value={this.state.term}. The only issue here would be that you cannot 100% guarantee that the value will be the same as term.