Controlled and Uncontrolled components in React!
We always need to handle our form state and almost every web app has one or more from
So How can we handle forms input value?
We have 2 ways to handle the input value, the first one is the Controlled Component and the second is Uncontrolled component
Ok, then what is the difference?
Let’s Start with the controlled component!
The controlled component is a way that you can handle the form input value using the state
and to change the input value there is only one way to change it is using setState
or useState
if you are using React Hooks
and you can change this state using one of the events like onChange
and when the user starts writing any character setState
or useState
will be called and update the state of this input then it will add the new value inside the input.
Example using react hooks (useState):
in the above example, we use the controlled component to handle the form input value using React Hooks
and every time you will type a new character, handleInputChange
is called and it takes in the new value of the input and sets it in the state then you can use this value and print it inside alert when submitting use handleSubmitButton
.
Now, let’s talk about Uncontrolled Components!
The uncontrolled component is like traditional HTML form inputs that you will not be able to handle the value by yourself but the DOM will take care of handling the value of the input and save it then you can get this value using React Ref
and for example, print it inside alert when submitting or play with this value as you want.
Example using react hooks (useRef):
Now you know what is the difference between the controlled component and the uncontrolled component
Maybe now the question that comes to your mind is when should I use the controlled component and when should I use the uncontrolled component?
Ok basically it’s up to you and up to your use case so for example
You can use the controlled component when you create
- Form validation so you always need to know the value of the input when typing to check if it’s a valid character or not!
- Disable the submit button unless all fields have valid data
- If you have a specific format like the credit card input
But if you don’t need any of that and think that the uncontrolled will be simpler for you, go for it.
Additional info
You can use Uncontrolled component to handle the form validation when typing but without update the input value with the state like the controlled but you can use setState
or useState
inside handle change to update the state then you can check this state if it’s valid or not and display an error message if it’s not valid but don’t use the state value inside the input value
And that’s it!
References…
React documentation (Controlled components)
React Documentation (Uncontrolled components)
Difference between controlled and uncontrolled components in react