Components in ReactJS: Controlled vs. Uncontrolled

There are two ways for React components to process form data. The first method involves handling the form data by leveraging the component’s state.
The term “controlled component” refers to this. The second option is to let the component’s DOM handle the form data on its own. The term “uncontrolled component” refers to this.

We’ll describe the distinction between controlled and uncontrolled components in React in this tutorial. We’ll also provide real-world examples to show how each function works.

HTML form components like <textarea/>, <select/> nd others frequently maintain their initial state and change it in response to user input. To make React apps interactive, state is used in every React component libraries. A component’s state changes over time as a result of user interactions with the programme after being initialized with a value.

Depending on your option, input values in React forms can be either uncontrolled or controlled. We will go over both methods of processing forms in React so you can understand the differences.

The best practice, which uses “controlled form fields,” contrasts with the HTML technique’s use of “uncontrolled form fields.”

What is Controlled Inputs?

Every character entered and even a backspace would count as a modification in a field with controlled inputs because adjustments and revisions are always being made.

Given that input fields don’t keep track of their internal state, the current value will be a props in React of the class component. The changes (in value) occuring in the input field must also be handled by a callback method (such onChange, onClick, etc.), making them manageable.

Image source:medium.com

Example

	
function App() {
  const [companyname, setCompanyname] = useState("");
  const [email, setEmail] = useState("");

  function onSubmit() {
    console.log("Company Name value: " + companyname);
    console.log("Email value: " + email);
  }
  return (
    <form onSubmit={onSubmit}>
      <input
        type="text"
        name="companyname"
        value={companyname}
        onChange={(e) => setCompanyname(e.target.value)}
      />
      <input
        type="email"
        name="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <input type="submit" value="Submit" />
    </form>
  );
}

The React state determines the values of our input elements name and email; as a result, the state serves as the input elements’ “single source of truth.” The App component seen above is a controlled component as a result.

Also Read: React State vs Props: Introduction & Differences

What is Uncontrolled Input?

There are no state updates or changes. It keeps track of its own internal state, so it essentially remembers what you entered in the field.
The ref keyword can be used to pull that value anytime it is required, allowing for its exploitation. Your input determines the output in uncontrolled inputs.

When the input values are not under control, there is no updating or alteration of statuses. Uncontrolled components maintain a record of their internal state, so they can recall the data you placed into a field.
By using the ref keyword to obtain that value anytime it is required, it can be changed. With uncontrolled inputs, the value you provide is the value you receive.

Image source:medium.com

Example

	
import React,{Component} from 'react';
class CompanyForm extends  React.Component {
    handleClick = () => {
      const companyname = this._companyname.value;
      alert('Hello ', companyname);
    }
   
    render() {
      return (
        <div>
          <input type="text" ref=
                {inputValue => this._companyname = inputValue}
             
            placeholder="Enter your Company Name " />
            <button onClick={this.handleClick}>
                OK
            </button>
        </div>
     );
    }
  }
 
export default CompanyForm;

Difference table between controlled and uncontrolled component

Differentiations
Controlled Components Uncontrolled Components
These components are governed by the component’s state and are predictable. Are Uncontrolled because data loss during the life cycle approaches
It accepts the prop’s current value. For their present values, a ref is used
Improved control over form values and data Has only a very small amount of control on form values and data
It allows validation control. It does not allow validation control.

Schedule an interview with React developers

Conclusion

You should now have a better knowledge of the distinction between controlled and uncontrolled components in the React framework. I hope you like this article.

In the end, React allows you to manage form data using either controlled or uncontrolled components. But bear in mind that the React documentation generally suggests using controlled components.

If you are searching for the best mobile app development company who have the React development team who assists you in your next React project. Consult our React Experts!

Frequently Asked Questions (FAQs)

1. Why do we utilize the controlled components in React?

In React, controlled components are those in which the forms data is handled by a component’s state. It will take the current value via props and will modify it via the callback methods. The parent component will manage its own state and pass the new values as props to the controlled component.

2. Why to use refs in React development?

Refs is the function which is given by React to access the DOM element and React element which you have created on your own. As they are used in cases where we wish to change the value of the child component, without utilizing props and all that.

3. Which are the three elements needed in the control system?

The basic elements which are needed in the control system are: error detector, controller, and output element.


Book your appointment now

Request a Quote