Controlled v/s Uncontrolled Component in React

Learn via video courses
Topics Covered

React revolutionizes UI development with its component-based approach, simplifying form interactions. It contrasts traditional DOM(Document Object Model) heavy methods by offering controlled and uncontrolled components, streamlining form data handling and enhancing performance. This article delves into these components, illustrating their practical applications.

What Are Controlled Components in React?

A component in react is referred to as controlled when we let react control the component for us. It means that the component controls the input form, and all of its changes are completely driven by event handlers like setState(). Also, the component controls the render and keeps the data of form in the component state.

Let us look at a diagrammatic explanation of the controlled component react :

flow of controlled component

Practically, when you are building a form dealing with user input, there will be HTML elements like textarea, select, and input. Instead of the DOM handling these fields, the form input is handled by the component in react. An internal state is maintained by these HTML elements and keeps on updating as the user changes the input. In accordance with that, the component that is wrapping the form will keep the mutable form data in its state and handles all the changes using the onChange method, which calls the setState() method.

The controlled component react takes all the values using props and reports the changes by using the callbacks. When we link the component state with the HTML elements, we are following "a single source of truth" as described by the documentation of the react. This means that react tracks all the changes with the help of the internal state and re-renders the component whenever there is a change.

Let's take an example of a form in a controlled component:

Each of the form elements contains a value. The above form contains typed fields that are input. The condition can also have a checkbox, and radiobutton and the updates are handled by the setState().

In the above example, we have react useState hook to create two states :

  • email
  • password

These states correspond to the value property of the email and password fields of the input form.

The email input element value is held by the email state. When the email value is being changed in the form by the user, the onChange event handle associated with the email input field will be triggered and all the changes will be handled using the setNamemethod.

The password input element value is held by the password state. When the password value is being changed in the form by the user, the onChange event handle associated with the password input field will be triggered and all the changes will be handled using the setPassword method.

Hence the value of the input field is controlled using the react state. The single source of truth for the input element is React state. Therefore, the above component is a controlled component.

Advantages of using controlled components in react:

The instant validation check is one of the major benefits of using the controlled component over the uncontrolled component in react.

You can have validation checks on every keystroke of the user when using controlled components in react. This is because we can access the input value at every time with the help of react state, whereas, in an uncontrolled component, the input value is only available when the form is submitted by the user. For example, we can perform a validation check on the user input (password type) where the requirement is that the input password should be at least eight characters and display a conditional message accordingly.

What Are Uncontrolled Components in React?

After studying the controlled components, it must be clear that the uncontrolled component react does not use state. Thus uncontrolled components do not depend on any state of input elements or any event handler. This type of component does not care about real-time input changes.

Let us look at a diagrammatic explanation of the uncontrolled component react:

flow of uncontrolled component

Hence you might be wondering then how we will get the input value in the component. Uncontrolled components react and act more like traditional HTML form elements. The data from the input fields are not stored in the react state, but the data is stored in the DOM itself. Instead of using any event handler setState() to update the value according to the changes by the user, we are provided with a ref to retrieve values from the DOM.

Refs in react environment work like a pointer that provides us access to the DOM nodes. We can say that an uncontrolled component is one that is closer to the actual vanilla JS (a low-level component).

Let's take an example of a form in an uncontrolled component:

In the above code, we have used ID attributes to get the value of the fields from the input form when it is submitted. We have assigned email and password ID to their respective fields. The above component is called uncontrolled because react state has no control over the value of the input fields of the HTML form.

Now let us refractor the above and use react ref to write the above component :

In the above code, we have created two react ref :

  • emailRef
  • passwordRef

These ref attributes correspond to the value of the email and password fields of the input form, respectively. Using react ref we can hold the instances of the HTML element in their .current property. Later using .current, we can get the value of input elements using the .value property.

Advantages of using uncontrolled components in react:

One of the benefits of react is that it brings a lot to the table. React is inclined more towards a View library. That is why react is one of the most popular frontend libraries, as it provides only an only-view approach using uncontrolled components as well as a model-view approach using controlled components in react. A higher level of abstraction from DOM API is one of the features of react. It depends on the use cases where to apply which approach.

So why react framework provides uncontrolled components? Simple: to help the developers integrate other libraries with react. Using uncontrolled components react will give access to the most basic web API, so you will be able to develop anything.

Controlled vs. Uncontrolled Components: Key Differences

Now that we have understood both the controlled and uncontrolled components in react, let us look at a few key differences between them :

  • In a controlled component react, state handles all the form data, whereas, in an uncontrolled component, the HTML form element data is managed by only the DOM.
  • If you are using a controlled component, you are in control of your form input values. The developer can decide what to insert or not and where to insert it.
  • It is a must to use react state in a controlled component to handle the dynamic form data. It is optional for the uncontrolled component to have a state, but it must use react Ref.
  • Controlled components are predictable since the component manages the state of the form elements.
  • Because the form elements may change or be impacted by external sources over the lifespan of a component, uncontrolled components are not predictable.
  • You can efficiently perform validation tests on each keystroke the user makes by using controlled components. Whatever alters the form components is irrelevant since their values are secure in our local state, where we carry out the validation.
  • You can perform validation on the input data only after the form is submitted in the uncontrolled components in react.

So now, which type of component should you use in a react app? The answer depends on the situation that is whichever component fits the liking of your project.

According to the official react documentation, the easiest way for us to build simple and reusable components is by using the controlled components. The controlled components provide a higher abstraction layer to work on. Hence we do not need to work on handling every element using DOM API. This reduces the cognitive effort needed to mentally understand the code and also works while building the real application and the related unit tests.

On the other hand, if you are working on a complex project which requires you to integrate react with libraries that do not follow React’s design pattern, then working directly with DOM API will help us more. Also, the uncontrolled components are harder to main and test. Hence both options have their valid cases, and we can use those according to our needs.

Difference Table Between Controlled and Uncontrolled Component

The difference in between controlled and uncontrolled components in react :

Controlled componentUncontrolled component
The parent component has held over the form data.The DOM itself holds control over the data.
It does not maintain its internal state.It maintains its internal state.
It allows validation control.It does not allow validation control.
It stores the current value in the form of props.It stores the current value using react ref.
It has better control over the form data.It has limited control over the form data.
Predictable because the component handles the form data at every step.Not predictable because form elements can lose their reference or may be changed/ affected by external sources during the lifecycle of components.

Revolutionize Your Node JS Exploration! Immerse Yourself in Our Full Stack Course, Crafted by Industry Visionaries. Enroll Now!

Conclusion

  • React supports two ways to handle the form data; it can either be a Controlled component or an Uncontrolled component.
  • React provides two distinctively flexible solutions, i.e., model-view (controlled) and only-view (uncontrolled).
  • Controlled components have a one-way data flow where the state inside the component serves as the single source of truth.
  • The parent component has held over the form data in the controlled component.
  • The DOM itself handles all the form data in an uncontrolled component.
  • It can become cumbersome to work with controlled components if there are many input fields on the page.
  • Controlled component react provides validation benefits on every keystroke of the user.
  • All the state changes in a controlled component are made with the help of the setState() method.
  • An uncontrolled component stores the current value of the form data using react ref.
  • Uncontrolled component react are helpful when we need to integrate react with other libraries which do not follow react design patterns.