Uncontrolled Components in React

Sneha Mallik
Last Updated: May 13, 2022

Introduction 

Uncontrolled components in React are ones for which the DOM(Document Object Model) handles the form data. The term "uncontrolled" points out the fact that React state has no control over these components.

The DOM has typically controlled and saved the values of form elements. To get the values from the DOM, we'll need to refer to the form elements' instance.

What is an uncontrolled component?

Uncontrolled components in React are the one that does not use an internal state to connect to the HTML elements that are included in it.

Instead, you'll obtain a direct reference to the HTML element in question, which you can utilize as you like. Consider an uncontrolled component to be a low-level component, similar to vanilla JavaScript(JS).

It is sometimes easier to mix React with non-React code when using uncontrolled components because the source of truth is kept in the DOM. If you want to be quick and dirty, it can also be somewhat less code. Otherwise, controlled components should be used.

Let us take the following example for uncontrolled components:-

import React, { useRef } from "react";

const UncontrolledComp = () => {
  const inputRef = useRef(null);

  const handleSubmit = (e) => {
    console.log(inputRef.current.value);
    e.preventDefault();
    };

  return (
    <form>
      <input type="text" ref={inputRef} />
      <button onClick={handleSubmit}>Submit Here!</button>
    </form>
  );
};

export default UncontrolledComp;

 

Output

We have a form with an input and a button in the above example. If we wish to refer to a DOM element in React, we can use the useRef hook. The useRef hook creates an object with a current property that contains the value. To get access to the value, we can set this reference to an element.

In other words, we'll utilize the useRef hook to construct a reference.

const inputRef = useRef(null);

 

Then we'll provide the reference to the <input> element.

<input type="text" ref={inputRef} />

 

When we submit the form, we can use the inputRef.current.value to get the value of the input.

Because React does not control the value of the input, it is termed an uncontrolled component. The element stores the value of the input internally. The value is directly retrieved from the <input> element.

React has several advantages, one of which is a higher level of abstraction from the DOM API (Application Programming Interface). So why would the framework allow you to construct uncontrollable components that go against everything it was built to do? The aim is simple: to make it easier for developers to integrate React with other libraries. By giving access to the most basic API, we'll be able to communicate in a universal language (sort of speaking) that will be understood by any other JS-based browser library.

Why not uncontrolled components?

The truth is that controlled components should be used as much as feasible. That's what the official React documentation suggests, and it's also the simplest method to create reusable components. Working with React's higher abstraction layer allows you to focus on your actual business logic without having to worry about the DOM API's internal workings. This method works for writing the program itself and the unit tests that go with it, and it even reduces the cognitive burden necessary to analyze your code mentally.

However, their use is not recommended when writing a regular React application. If you're working on something else, such as interacting with other libraries that don't follow React's design pattern, relying on a lower-level layer, such as the DOM API, will help you speak the same language as afterwall, Vue, Reat, Angular, and any other front-end framework.

Yes, there is a genuine use case for uncontrolled components in React, and yes, adding them to your project will make it more challenging to test and maintain, but you have the option, which is the benefit of using React.

When to use uncontrolled components?

Controlled components are a convenient and powerful way to implement forms the "React way," but they aren't always ideal. It still depends on the strategy or scenario you're attempting to accomplish or overcome.

If we only need to develop a very simple form, such as one that only asks a user to enter his first and last name, then an uncontrolled component implementation should be enough for it. During form submission, we'll generally just need to get and validate the values regardless.

However, suppose we want automatic field validations, or to have the ability to disable the submit button if invalid input is entered, or even using dynamic inputs for the form. In that case, we should use React's controlled components. Furthermore, if we start applications with uncontrolled components in React, migrating to controlled components isn't difficult.

Difference between Controlled and Uncontrolled Components in React

Uncontrolled ComponentsControlled Components
It helps in maintaining the internal states.It does not help in maintaining the internal states.
The DOM itself controls the data in uncontrolled components.The parent component always controls data.
The current values are stored in a ref.It accepts the value it currently has as a prop.
Validation control is not possible.Validation control is possible.
It only offers a limited amount of control on the data and form elements.It has more control over the data and form elements.

Frequently Asked Questions

  1. Why does the React documentation encourage utilizing controlled components to create forms?

Ans: According to the React documentation, using a controlled component is the best option in most circumstances.

Credit - React Documentation

One of the most significant advantages of utilizing controlled components over uncontrolled components in React is ‘instant validation checks’.

When utilizing an uncontrolled component, the input value is only accessible when the form is submitted. When using a controlled component, on the other hand, we always have access to the value. As a result, it's simple to add validation tests to each keystroke.

 

2. When should the controlled component be used, and when should the uncontrolled component be used?

Ans: Basically, it's up to you and your use case. 

For instance, you can utilize the controlled component so that when creating: 

  • Form validation, you always know the value of the input when typing to see if it is a valid character or not!
  • Unless all fields have correct data, you can disable the submit button.
  • If you need a particular format, such as credit card input.

However, if you don't require any of this and think that the uncontrolled components in React will be more convenient for you, go for this.

Key Takeaways

In this blog, we have learned the concepts of uncontrolled components. Uncontrolled components in React require us to use a lower level API to achieve the results, which can also be obtained using controlled components working with React's internal state. 

Unless you need to perform something unusual with additional libraries, you should stick to the good old controlled components.

We can use the uncontrolled component to handle form validation when typing but without updating the input value with the state like in the controlled component. Instead, you can use 'setState' or 'useState' inside handle change to update the state and then check if it's valid or not and display an error message if it's not valid.

Enroll in our Advance Front-end Web Development Course- React.js to deeply understand the concept of uncontrolled components in React of Web Development. 

Credits: GIPHY

Happy Developing!

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think