Mapagam
  • JavaScript 
  • Web APIs 
  • TypeScript 
  • React 

How to Handle Forms in React (With Controlled & Uncontrolled Inputs)

Posted on April 14, 2025 • 7 min read • 1,291 words
Share via

Learn how to handle forms in React with controlled & uncontrolled inputs. Explore key concepts, implementation examples, and best practices.

On this page
1. Introduction to Forms in React 1.1. Why Forms Matter in Web Development 1.2. What Are Controlled and Uncontrolled Inputs? 2. Controlled Components in React 2.1. What Is a Controlled Component? 2.2. How Controlled Components Work 2.3. Advantages of Controlled Components 2.4. Implementing Controlled Components 2.5. Practical Example: A Controlled Form 2.6. Common Pitfalls in Controlled Components 3. Uncontrolled Components in React 3.1. What Is an Uncontrolled Component? 3.2. How Uncontrolled Components Work 3.3. Advantages of Uncontrolled Components 3.4. Implementing Uncontrolled Components 3.5. Practical Example: An Uncontrolled Form 3.6. Common Pitfalls in Uncontrolled Components 4. When to Use Controlled vs. Uncontrolled Components 4.1. Factors to Consider 4.2. Use Cases for Controlled Components 4.3. Use Cases for Uncontrolled Components 5. Best Practices for Form Handling in React 5.1. Managing State Efficiently 5.2. Validating Form Data 5.3. Improving User Experience with Form Libraries 6. Conclusion

Forms are one of the most essential aspects of user interaction in web applications. Whether it’s collecting feedback, user authentication, or other data from users, forms are a central feature. React, a popular JavaScript library, provides two methods for handling forms: controlled components and uncontrolled components. Both of these approaches come with their pros and cons.

1. Introduction to Forms in React

Forms are an essential part of nearly every web application. They collect, manage, and send data to backend services. React simplifies the way forms are handled, making it easier to create interactive, responsive, and dynamic forms.

1.1. Why Forms Matter in Web Development

Forms are everywhere on the web. Whether it’s logging in to an account, submitting feedback, or making a purchase, forms act as a communication bridge between the user and the web application. How forms are handled can significantly impact the user experience, making form management a crucial part of front-end development.

1.2. What Are Controlled and Uncontrolled Inputs?

In React, forms can be handled in two main ways: controlled components and uncontrolled components. The difference between the two lies in how the form’s data is managed and updated.

  • Controlled Inputs: These are inputs whose values are controlled by the React state.
  • Uncontrolled Inputs: These are inputs that manage their own state internally and are not directly tied to React’s state.

2. Controlled Components in React

2.1. What Is a Controlled Component?

A controlled component is an input element whose value is controlled by the React state. In other words, React has full control over the form’s data. Every time a user types into a form field, React’s state gets updated, and this update propagates back to the component, making the input’s value always consistent with the React state.

2.2. How Controlled Components Work

In controlled components, the value of an input field is bound to the state of a component. This is done by setting the value attribute of the input element to a state variable and updating the state when the user interacts with the input.

Example:

import React, { useState } from "react";

function ControlledForm() {
  const [inputValue, setInputValue] = useState("");

  const handleChange = (event) => {
    setInputValue(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(inputValue);
  };

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

2.3. Advantages of Controlled Components

  • Predictability: The form’s state is controlled by React, which allows for easier debugging and tracking.
  • Validation: You can easily validate form data before submission, as all the data is stored in the React state.
  • Dynamic Forms: Since React controls the form, dynamic changes can be made easily. For instance, form fields can be added, removed, or modified without difficulty.

2.4. Implementing Controlled Components

To implement controlled components in React:

  1. Create a state variable to hold the input value.
  2. Bind the value attribute of the form element to the state variable.
  3. Use an onChange handler to update the state when the input value changes.

2.5. Practical Example: A Controlled Form

import React, { useState } from "react";

function RegistrationForm() {
  const [formData, setFormData] = useState({
    username: "",
    email: "",
    password: "",
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prevData) => ({
      ...prevData,
      [name]: value,
    }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(formData);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Username:
        <input
          type="text"
          name="username"
          value={formData.username}
          onChange={handleChange}
        />
      </label>
      <label>
        Email:
        <input
          type="email"
          name="email"
          value={formData.email}
          onChange={handleChange}
        />
      </label>
      <label>
        Password:
        <input
          type="password"
          name="password"
          value={formData.password}
          onChange={handleChange}
        />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

2.6. Common Pitfalls in Controlled Components

  • Performance Issues: In large forms, managing every input field in the state can cause performance issues. For complex forms, it’s advisable to use form management libraries like Formik or React Hook Form.
  • Verbose Code: Writing form handling logic for each input field can lead to verbose and repetitive code.

3. Uncontrolled Components in React

3.1. What Is an Uncontrolled Component?

An uncontrolled component is a form element where React does not directly manage the value of the input. Instead, the input maintains its own internal state. In this case, you don’t need to update the React state each time the input changes.

3.2. How Uncontrolled Components Work

In uncontrolled components, the value of the input is stored in the DOM itself rather than in the React state. React accesses this value using refs.

Example:

import React, { useRef } from "react";

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

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`Input Value: ${inputRef.current.value}`);
  };

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

3.3. Advantages of Uncontrolled Components

  • Simplicity: For simple forms, uncontrolled components are often easier to implement since you don’t need to manage the state for each form element.
  • Less Overhead: Since the form’s state isn’t managed by React, it can be faster for simpler forms with less state management overhead.

3.4. Implementing Uncontrolled Components

To implement uncontrolled components in React:

  1. Use ref to get a reference to the form element.
  2. Access the form value via the ref when needed, usually on form submission.

3.5. Practical Example: An Uncontrolled Form

import React, { useRef } from "react";

function FeedbackForm() {
  const nameRef = useRef();
  const emailRef = useRef();
  const messageRef = useRef();

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log({
      name: nameRef.current.value,
      email: emailRef.current.value,
      message: messageRef.current.value,
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" ref={nameRef} />
      </label>
      <label>
        Email:
        <input type="email" ref={emailRef} />
      </label>
      <label>
        Message:
        <textarea ref={messageRef}></textarea>
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

3.6. Common Pitfalls in Uncontrolled Components

  • Limited Validation: Since React does not manage the form data, validation and dynamic updates can be more challenging.
  • Inconsistent UI: With uncontrolled components, the form data might not always be in sync with React’s state, potentially leading to UI inconsistencies.

4. When to Use Controlled vs. Uncontrolled Components

4.1. Factors to Consider

  • Complexity: Use controlled components for complex forms where you need full control over the form data.
  • Performance: For simpler forms, uncontrolled components may be more performant as React does not need to constantly update the state.

4.2. Use Cases for Controlled Components

  • Forms with dynamic validation or conditional fields.
  • When you need to keep the form data in sync with other parts of your application.

4.3. Use Cases for Uncontrolled Components

  • Simple forms with minimal validation and logic.
  • Situations where performance is a concern, and React state management might introduce unnecessary overhead.

5. Best Practices for Form Handling in React

5.1. Managing State Efficiently

Use state management libraries like React Hook Form or Formik to simplify form handling. These libraries help manage state, validation, and submissions more efficiently.

5.2. Validating Form Data

Form validation is essential for ensuring that the data submitted is accurate and complete. Libraries like Formik and React Hook Form provide built-in support for validation, making it easier to validate form inputs.

5.3. Improving User Experience with Form Libraries

React form libraries help manage form state, validation, and submission more effectively. They also offer features like field-level validation, easy integration with UI frameworks, and better error handling.

6. Conclusion

Handling forms in React is an essential skill for any React developer. Whether you choose controlled components for complex forms or uncontrolled components for simpler forms, React provides flexibility in form management. By understanding the differences, advantages, and practical implementation of both approaches, you can create efficient and user-friendly forms in your applications.

For complex forms, use controlled components for better validation and state management. For simpler forms, consider uncontrolled components for better performance and reduced complexity. Regardless of the approach, best practices like using form libraries and managing state efficiently can significantly improve your React forms’ performance and user experience.

React Forms   Controlled Components   Uncontrolled Components   React Form Handling   Form Validation in React  
React Forms   Controlled Components   Uncontrolled Components   React Form Handling   Form Validation in React  
 How to Style React Components: CSS, Styled Components & More
React Lists and Keys Explained (Why You Should Use Them) 
On this page:
1. Introduction to Forms in React 1.1. Why Forms Matter in Web Development 1.2. What Are Controlled and Uncontrolled Inputs? 2. Controlled Components in React 2.1. What Is a Controlled Component? 2.2. How Controlled Components Work 2.3. Advantages of Controlled Components 2.4. Implementing Controlled Components 2.5. Practical Example: A Controlled Form 2.6. Common Pitfalls in Controlled Components 3. Uncontrolled Components in React 3.1. What Is an Uncontrolled Component? 3.2. How Uncontrolled Components Work 3.3. Advantages of Uncontrolled Components 3.4. Implementing Uncontrolled Components 3.5. Practical Example: An Uncontrolled Form 3.6. Common Pitfalls in Uncontrolled Components 4. When to Use Controlled vs. Uncontrolled Components 4.1. Factors to Consider 4.2. Use Cases for Controlled Components 4.3. Use Cases for Uncontrolled Components 5. Best Practices for Form Handling in React 5.1. Managing State Efficiently 5.2. Validating Form Data 5.3. Improving User Experience with Form Libraries 6. Conclusion
Follow me

I work on everything coding and technology

   
Mapagam
Mapagam is your go-to resource for all things related to frontend development. From the latest frameworks and libraries to tips, tutorials, and best practices, we dive deep into the ever-evolving world of web technologies.
Licensed under Creative Commons (CC BY-NC-SA 4.0).
 
Frontend
JavaScript 
Web Api 
TypeScript 
React 
Social
Linkedin 
Github 
Mapagam
Link copied to clipboard
Mapagam
Code copied to clipboard