What are Controlled Components in React?

This article provides a clear and concise explanation of controlled components in React. You will learn what controlled components are, how they work, how they differ from uncontrolled components, and how to implement them in your projects with practical code examples.

Understanding Controlled Components

In React, a controlled component is an input form element whose value is controlled by the React state. Instead of the browser’s Document Object Model (DOM) maintaining the state of the input, the React component itself keeps track of the input’s current value in its internal state.

In a traditional HTML form, form elements like <input>, <textarea>, and <select> typically maintain their own state and update it based on user input. In React, a controlled component overrides this default behavior, making the React state the “single source of truth” for the input’s data.

How Controlled Components Work

To create a controlled component in React, you need to follow three main steps:

  1. Initialize State: Define a state variable using the useState hook to store the input’s value.
  2. Bind the Value: Set the value attribute of the input element to your state variable.
  3. Handle Changes: Create an onChange event handler that updates the state variable whenever the user types or changes the input value.

Here is a basic code example demonstrating a controlled text input:

import React, { useState } from 'react';

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

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

  const handleSubmit = (event) => {
    event.preventDefault();
    alert('A name was submitted: ' + name);
  };

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

export default NameForm;

In this example, every keystroke triggers the handleChange function, which updates the React state. React then re-renders the component, ensuring the input display is always in sync with the state.

Why Use Controlled Components?

Controlled components offer several advantages over uncontrolled components, particularly when dealing with complex form interactions:

Controlled vs. Uncontrolled Components

While controlled components are the standard approach in React, you may sometimes encounter uncontrolled components.