Controlled Vs. Uncontrolled Component: The form is one of the most-used HTML elements in web development. Since the introduction of React, the way forms have been handled has changed in many ways.
In React, there are two ways to handle form data in our components. The first way is by using the state within the component to handle the form data. This is called a controlled component. The second way is to let the DOM handle the form data by itself in the component. This is known as an uncontrolled component.
In this tutorial, we’ll explain the difference between controlled and uncontrolled components in React. We’ll also demonstrate how each works with practical examples.
Controlled Component
A controlled component is bound to a value, and its changes will be handled in code by using event-based callbacks. Here, the input form element is handled by the react itself rather than the DOM. In this, the mutable state is kept in the state property and will be updated only with the setState() method.
Controlled components have functions that govern the data passing into them on every onChange event that occurs. This data is then saved to state and updated with the setState() method. It makes component better control over the form elements and data.
Uncontrolled Component
It is similar to the traditional HTML form inputs. Here, the form data is handled by the DOM itself. It maintains its own state and will be updated when the input value changes. To write an uncontrolled component, there is no need to write an event handler for every state update, and you can use a ref to access the value of the form from the DOM.
Difference table between controlled and uncontrolled component
Controlled | Uncontrolled |
It does not maintain its internal state. | It maintains its internal states. |
Here, data is controlled by the parent component. | Here, data is controlled by the DOM itself. |
It accepts its current value as a prop. | It uses a ref for their current values. |
It allows validation control. | It does not allow validation control. |
It has better control over the form elements and data. | It has limited control over the form elements and data. |
Conclusion
In this tutorial, we zoomed in on form elements and form data, both generally and within the React framework. Next, we introduced two ways to handle form data in React components: controlled and uncontrolled. Finally, we took a deep dive into both types of components and demonstrated how they behave with practical examples.
Read more
React create-react app
Component API in ReactJS
React Forms | Controlled and Uncontrolled Component