Controlled component vs Uncontrolled component in ReactJS
Followings are the main difference between the controlled component and an uncontrolled component
Source of value
In the Controlled component, the value of the component is stored in the state object. So when you make any change in component, an event handler will be called which will change the value of the component in the state object. That value will be pushed to DOM via ReactJS.
So in a controlled component, you are pushing the value to DOM from state object.
In the Uncontrolled component, the source of the value is DOM. When you make any change in component, DOM handles that change ( like in non-react applications ). ref is used to getting the value of component.
So in the Uncontrolled component, you are pulling the data from DOM.
This point is derived from the above point.
In the Controlled component, ReactJS is handling all the work ( handling the event, change value in state and push the value ). So it is called a controlled component.
In the Uncontrolled component, DOM is handling all the work ( change the value ). It is not controlled by ReactJS. So it is called an Uncontrolled component.
There is a lot of difference in features provided by the controlled component and uncontrolled component.
|Features||Controlled Component||Uncontrolled Component|
|The value retrieved on Submit||Yes||Yes|
|Validation on Submit||Yes||Yes|
|Validation on change of value||Yes||No|
|Disable submit button on condition||Yes||No|
|Multiple inputs on single data||Yes||No|
Which one you should use?
It depends on the situation.
ReactJS's official document suggests a controlled component should be used ( unless it is input type file ). If you are creating the application from scratch, the controlled component should be used.
If you need features provided by the controlled component, use that.
If you have a non-react application and you are converting it to ReactJS, then you can use an uncontrolled component. As always, input type file is always an uncontrolled component.
In this section, you learned about the difference between Controlled component and Uncontrolled component in ReactJS.
In the next section, you will learn about the Forms in ReactJS.