Skip to main content

Command Palette

Search for a command to run...

Understanding Controlled and Uncontrolled Components in React

Published
β€’3 min read
Understanding Controlled and Uncontrolled Components in React
R

Frontend developer who weaves creativity and code, book lover, avid traveller and a tech enthusiast

Handling form is an integral part in React as most web apps rely a lot on the user input. React provides two approaches of handling form. They are via:

  • Controlled component

  • Uncontrolled component

Each method has their own pros and cons. Lets discuss them now

πŸ”† Controlled Component

A component is called controlled when it is entirely controlled by React’s state.

Read more about state on this link

For example: whenever we create any input field or text area, their value comes from state.

When state changes, a component re-renders. As a result, we get the updated value.

βœ… When to use

  1. You are working on a complex form.

  2. You want proper validations.

❌ When not to use

  1. You have a simple form.

  2. You have single input fields or very few input fields.

πŸ”₯ Benefits of controlled component

  1. Since value is controlled by state, we have full control.

  2. Immediate access to the form data and proper validation.

πŸ†’ Example

import {  useState } from "react";

const Controlled = () => {
  const [formData, setFormData] = useState({
    firstName: "",
    lastName: "",

  });

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

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

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        name="firstName"
        value={formData.firstName}
        onChange={handleChange}
        placeholder="Enter first name"
      />
      <input
        type="text"
        name="lastName"
        value={formData.lastName}
        onChange={handleChange}
        placeholder="Enter last name"
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default Controlled;

πŸ”† Uncontrolled Component

A component is called uncontrolled when the forms are handled by the DOM itself, not the React state.

Unlike controlled components, where form data is managed through React state and updated via setState, ref is used to access the input elements.

Unlike state, the component does not re-render when used ref as it remembers the past value.

βœ… When to use

  1. You have a small form with few inputs.

  2. When you are working with non-React code.

❌ When not to use

  1. You have complex forms.

  2. You want full control and validation.

πŸ”₯ Benefits of uncontrolled component

  1. Requires less code than controlled component.

  2. They also perform better and feel more natural to React beginners who are familiar with HTML.

πŸ†’ Example

import { useRef } from "react";

const Uncontrolled = () => {
  const fnameRef = useRef(null);
  const lnameRef = useRef(null);

  const handleSubmit = (e) => {
    e.preventDefault();

    const firstName = fnameRef.current?.value;
    const lastName = lnameRef.current?.value;

    console.log("Form data", firstName, lastName);
  };

  return (
    <form className="controlled" onSubmit={handleSubmit}>
      <h2>Uncontrolled approach</h2>
      <input type="text" ref={fnameRef} placeholder="Enter first name" />
      <input type="text" ref={lnameRef} placeholder="Enter last name" />

      <button type="submit">Submit</button>
    </form>
  );
};

export default Uncontrolled;

✨ Conclusion

In a nutshell, use controlled approach when you have a complex dynamic form and need more control. Use uncontrolled approach when you are dealing with a simple form.

React

Part 1 of 5

My goal is to make complex concepts easier to grasp, especially for beginners who are just getting started with React. No jargon, no fluff β€” just clear, beginner-friendly content to help you build confidence in React step by step.

Up next

Preventing Prop Drilling in React Using Zustand: A Shopping Cart Example

While building React apps, you’ve probably faced a situation where you need to pass props from Parent β†’ Child β†’ Grandchild, even though the intermediate components don’t really use those props. This common issue is called Prop Drilling. To be more cl...

More from this blog

Raj's Blog

25 posts

I am a passionate Frontend Developer who loves to make internet beautiful and useful. I love to share what I have learnt and love to learn new techs. A bibliophile, tech enthusiast and a cynophilist.