Understanding Controlled vs. Uncontrolled Inputs in React: What You Need to Know

Understanding Controlled vs. Uncontrolled Inputs in React: What You Need to Know

Maximizing React's Form Handling Potential by Knowing When to Use Controlled and Uncontrolled Input Elements

·

5 min read

When it comes to building forms in React, there are two main ways to handle user input: controlled inputs and uncontrolled inputs. Controlled inputs refer to inputs that are fully managed by React, while uncontrolled inputs allow the DOM to manage the input values. Both methods have their own benefits and drawbacks, and choosing the right one for your specific use case can be crucial to maximizing your app's performance and maintainability.

In this blog post, we'll explore the differences between controlled and uncontrolled inputs in React, their use cases, and the pros and cons of each approach. We'll also provide practical examples and tips on when to use one over the other, so you can make informed decisions when building forms in your React applications. Whether you're new to React or a seasoned developer, understanding these two approaches can help you improve your code's performance and user experience.

Uncontrolled Inputs

In React, uncontrolled inputs are input elements that are not fully managed by React. Instead, the DOM handles the input values, and React can only access them through refs. Uncontrolled inputs are useful when you need to quickly handle simple form inputs without adding extra complexity to your code.

Here's a simple example of an uncontrolled input in React:

import React, { useRef } from "react";

function UncontrolledInput() {
  const inputRef = useRef(null);

  function handleSubmit(event) {
    event.preventDefault();
    // Get the value of the input using the ref
    const value = inputRef.current.value;
    // Do something with the value
    console.log("Submitted value:", value);
  }

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

In this example, we have an UncontrolledInputExample component that renders a form with a single text input. We create a ref using the useRef hook and attach it to the input using the ref prop.

When the user submits the form, the handleSubmit function is called. It prevents the default form submission behavior and gets the value of the input using the inputRef.current.value property.

By using an uncontrolled input in this way, we can quickly handle simple form inputs without adding extra state variables or event handlers to our component. However, it's important to note that we have less control over the input value, and we can't perform any complex actions or validations on it.

Uncontrolled inputs are simple and straightforward to use, making them a good choice for handling simple forms or quick inputs where you don't need full control over the input values. Uncontrolled inputs require less code to set up and manage, making them quicker and easier to implement than controlled inputs.

Since uncontrolled inputs are not stored in the component state, it can be harder to synchronize them with other parts of your app's state, making it more challenging to track changes over time.

Controlled Inputs

In React, controlled inputs are input elements (like text fields, checkboxes, etc.) that are managed by React. This means that the value of the input is stored in the component's state, and any changes to the input are handled by React. Controlled inputs are useful when you need to perform some action or validation on the input value, or when you want to synchronize the input value with other parts of your app's state. Here is a basic example of a controlled input in React :

import React, { useState } from "react";

function ControlledInput() {
  const [value, setValue] = useState("");

  function handleChange(event) {
    setValue(event.target.value);
  }

  function handleSubmit(event) {
    event.preventDefault();
    // Do something with the value
    console.log("Submitted value:", value);
  }

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

In this example, we have a ControlledInputExample component that renders a form with a single text input. The value of the input is stored in the value state variable using the useState hook.

The handleChange function is called whenever the user types something into the input. It updates the value state variable with the new input value using the setValue function.

Finally, the handleSubmit function is called when the user submits the form. It prevents the default form submission behavior and logs the submitted value to the console.

By using a controlled input in this way, we have full control over the input's value and can perform any necessary actions or validations on it before submitting the form.

More control and flexibility: Controlled inputs give you full control over the input value and allow you to perform any necessary actions or validations on it before submitting the form. Controlled inputs provide a more structured approach to handling complex forms with many inputs and validations, making it easier to manage and update your form over time.

More complex code: Controlled inputs require more code and event handlers to manage, making them more complex and harder to read than uncontrolled inputs.

Conclusion: Which one is better to use?

There isn't a definitive answer to whether controlled or uncontrolled inputs are "better" to use, as both have their own benefits and drawbacks.

Controlled inputs provide more control and flexibility over the input values and can be useful for handling complex forms or performing validations on the input values. However, they can add extra complexity to your code and require more event handlers and state variables to manage.

Uncontrolled inputs are generally simpler to use and require less code. They are useful for handling simple forms or quick inputs where you don't need full control over the input values. However, they provide less control and flexibility over the input values, and you can't perform complex actions or validations on them.

Ultimately, the choice between controlled and uncontrolled inputs depends on your specific use case and the complexity of your form. If you have a complex form with many inputs and validations, controlled inputs might be a better choice. On the other hand, if you have a simple form with only a few inputs, uncontrolled inputs might be a simpler and more straightforward approach.