NashTech Blog

React Form Handling: Controlled vs. Uncontrolled Components

Table of Contents
react

Controlled and uncontrolled components are the two main methods of handling form inputs that you may come across when creating forms in React. The way these methods deal with the form data and the connection between the form elements and the component state varies.

To help you decide which strategy is ideal for your upcoming React project, we’ll explain both ideas, weigh their advantages, and walk you through several examples in this blog article.

What Are Controlled Components in React?

Controlled Components: The React Way

A controlled component is a form element whose value is controlled by the state of the React component. Essentially, React takes control of the input fields, meaning the component state is the single source of truth for the input value.

In a controlled component, every time a user interacts with a form field, the corresponding value is updated in the state, which then triggers a re-render of the component to reflect the updated value.

Key Characteristics of Controlled Components:

  • The form element’s value is tied to the component’s state.
  • You must define an onChange handler to capture user input and update the state.
  • React re-renders the component whenever the state is updated.

Example of a Controlled Component:

import React, { useState } from 'react';

function MyForm() {
  const [name, setName] = useState('');

  const handleChange = (event) => {
    setName(event.target.value); // Update state with the input value
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    alert('Submitted Name: ' + name);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={name} onChange={handleChange} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;

In this example:

  • The value of the input field is tied to the name state.
  • The handleChange function updates the state whenever the user types in the input field.

What Are Uncontrolled Components in React?

Uncontrolled Components: Letting the DOM Handle It

In contrast, an uncontrolled component is a form element whose value is managed by the DOM itself, not by React state. Rather than setting the value as you would with a controlled component, the input field keeps track of its own state, and you only read the value when necessary.

This approach is more akin to traditional HTML forms, where form elements manage their own state and React simply handles the submission logic.

Key Characteristics of Uncontrolled Components:

  • The form element’s value is stored in the DOM, not in React state.
  • You use ref to access the form element’s value, rather than using state or onChange handlers.
  • React does not re-render the component each time the input changes.

Example of an Uncontrolled Component:

import React, { useRef } from 'react';

function MyForm() {
  const nameInput = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    alert('Submitted Name: ' + nameInput.current.value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" ref={nameInput} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;

In this example:

  • We use useRef to get a reference to the input element.
  • On form submission, we access the value of the input directly from the DOM using nameInput.current.value.

Comparing Controlled and Uncontrolled Components

FeatureControlled ComponentsUncontrolled Components
Data SourceComponent stateDOM
Re-renderingTriggers re-renders on each state updateNo re-rendering unless explicitly triggered
Use of RefNot requiredUses ref to access form values
State ManagementReact manages stateForm values managed by the DOM
Best Use CasesComplex forms, dynamic interactions, validationSimple forms or when performance is critical

When to Use Controlled Components vs. Uncontrolled Components

Use Controlled Components When:

  • You need to manage or validate form input dynamically (e.g., showing error messages, real-time validation).
  • You want to perform complex logic based on form data (e.g., enable/disable submit button based on input).
  • You need the form data to be tightly coupled with the component state.

Use Uncontrolled Components When:

  • You don’t need to manage every aspect of the form input and just need to submit the data.
  • You prefer to minimize re-renders, as uncontrolled components don’t trigger re-renders when their value changes.
  • You have a simple form that doesn’t require sophisticated state management.

Best Practices for Form Handling in React

  1. Use controlled components when possible: Controlled components give you full control over form data and make it easier to handle validation, formatting, and other dynamic behaviours.
  2. Use refs for simpler forms: Uncontrolled components can be useful for forms that don’t need to interact with the component’s state too much. For example, simple forms like contact forms or search bars may not need to update the state on every keystroke.
  3. Consider performance: For very large forms with lots of input fields, uncontrolled components may perform better since they don’t trigger re-renders on every user interaction.

Conclusion

When working with forms in React, both controlled and uncontrolled components are useful tools, and each has a place based on your particular requirements. While uncontrolled components provide a less complex and performance-heavy solution for basic forms, controlled components provide you greater power and flexibility by enabling you to directly manage the input data through React’s state.

The intricacy of your form, the degree of control you need over the input data, and your performance needs will ultimately determine whether you use controlled or uncontrolled components. Knowing the advantages and disadvantages of each strategy will help you work with forms in React more confidently.

For more such blogs and updates follow Front-end Competency.

Follow NashTech Blogs for more amazing blogs.

Picture of kaushikichopra

kaushikichopra

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

Scroll to Top