Controlled vs Uncontrolled Components

Controlled vs Uncontrolled Components

As a React developers, we are constantly working with components that need and are always get to interact with the user instead of just displaying them on the page. And to register these components and the user inputs we essentially bind an event handler to such components, ex. Input.

function onInputChange(){
console.log(event.target.value)
}

<label>User Input </label>
<input type="text" onChange={onInputChange} />

And in this blog, we will continue down this path of event handler and we are going to look at a kind of little bit more challenging concept around eventHandlers.

Controlled vs UnControlled

At present we have created as shown above an uncontrolled input element. In particular, the text input here is an Uncontrolled Element.

And In general, as React Developers we tend to work with controlled components more that the uncontrolled components.

const [inputTerm, setInputTerm] = useState("")

<input type="text" value={inputTerm} onChange={(e)=>setInputTerm(e.target.value)} />

Here, on each time when user types in something, the event onChange is going to fire and it is essentially going to update that state inputTerm for us as the current value in the input field.

Also on the input, we are going to state a new prop as value which is assigned as the current state value.

As you can even note, it already, there is as such not a major change that we have applied, however, we can't even realize any change on the component on the browser yet.

What's is the point in including the state? all these changes we did?

Flow:

  1. User Types in Input.

2.Callback gets invoked.

3.We call the setInputTerm with new value.

4.Component Re renders.

5.Input is told what its value is ( coming from the state ).

In result, the above flow is exactly what constitutes a controlled component. We cannot call a component Controlled without binding its values or handling all of its events in our state variables. Otherwise, we can try to understand this until and unless we have tied the HTML elements with our React variables, i.e. a state, the " React World " will not be aware of anything in the " HTML World ".

And for case, when we have made our user input as a controlled component, we can essentially take out whatever value which was until now, in uncontrolled component, was inside "HTML World", directly in "React World" Because we have tightly bound both the value/data to a single source of truth. React State.

Well, that's it! We have successfully created a controlled component. Let me know what you think.

Thanks for Reading. May the code be with you.