NashTech Blog

Form Handling in React: Controlled vs Uncontrolled Components

Table of Contents
Form Handling in React: Controlled vs Uncontrolled Components

Introduction

Form management is a common and necessary task in web development. Whether you’re creating a small form or a complex multi-step process, React provides a flexible and powerful way to manage user input. But there are two main ways to manage forms in React: controlled components and non-controlled components. Understanding the differences between these two approaches and knowing when to use each can greatly improve your form management and overall React development experience. In this blog, we’ll dive into both controlled and non-controlled components and will explore the pros and cons and demonstrate how to implement each approach in React.

What Are Controlled Components?

In React, a controlled component is a component in which the form element (such as <input>, <textarea>, and <select>) is controlled by the React state. This means that the form element’s value is bound to the React element’s state. Any Actions made to the input (by the user) trigger event handlers that update the component’s state which then renders the component with the new value.

How Controlled Components Work:

State management: The value of the input field is controlled by React’s state.

Event Handling: You use React’s event handlers (such as onChange) to update the state.

Single source of truth: React state is a single source of truth for form data.

Example of Controlled Component

import React, { useState } from 'react';

const ControlledForm = () => {
  const [inputValue, setInputValue] = useState('');

  const handleChange = (e) => {
    setInputValue(e.target.value);  // Update the state with the input's value
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    alert('Form submitted with value: ' + inputValue);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input 
          type="text" 
          value={inputValue}  // The value is controlled by state
          onChange={handleChange}  // Handle the change event
        />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
};

export default ControlledForm;

What Are Uncontrolled Components?

Uncontrollable components are those where the form element manages its own state internally, rather than relying on React state. With uncontrollable components you don’t explicitly bind form fields to React’s state, but instead interact directly with the DOM, using references to read form field values ​​when needed.

How Uncontrolled Components Work:

DOM-based: The value of the form element is managed by the DOM, not React state.

Refs: You use React’s ref to directly access the DOM node and read the value when needed (e.g., on form submission).

Less React-centric: You don’t need to handle onChange events to update the state.

Example of Uncontrolled Component

import React, { useRef } from 'react';

const UncontrolledForm = () => {
  const inputRef = useRef();

  const handleSubmit = (e) => {
    e.preventDefault();
    alert('Form submitted with value: ' + inputRef.current.value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input 
          type="text" 
          ref={inputRef}  // Use ref to access the DOM node
        />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
};

export default UncontrolledForm;

Conclusion

When it comes to managing forms in React, the choice between controlled and uncontrolled components depends on your needs. Controlled components provide more flexibility and allow you to more tightly manage form data. This makes it suitable for complex forms, real time monitoring and if you want to interact with form data. Uncontrolled components provide better performance and simplicity for simple forms or when you don’t need them. There’s no need to manipulate form data beyond submission.

Understanding when to use each method will help you optimize your React app and help you manage your forms more efficiently. Whether you choose controlled components or uncontrolled components or a combination of both, react gives you the tools you need to create powerful, easy-to-use forms.

Finally, for more such updates and to read more about such topics, please follow our LinkedIn page Frontend Competency.

Picture of Aanchal

Aanchal

Aanchal Agarwal is a Sr. Software Consultant at NashTech. Her practice area is web development. She is recognized as a multi-talented, multitasker, and adaptive to the different work environments. Her hobbies include watching movies, listening to music, and traveling. She likes to read books and explore new things.

Leave a Comment

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

Suggested Article

Scroll to Top