Skip to main content
TOPIC 8 OF 8 · 2 MIN READ

Controlled vs. Uncontrolled Components in React

In React, form elements like inputs, textareas, and select elements can be managed in two ways: Controlled Components (React fully manages the state) and Uncontrolled Components (the DOM itself manages the state). Understanding these two approaches is crucial for building forms in React effectively.

Key concepts

Controlled Components

React fully manages the state of the form element. The component's state acts as the 'single source of truth'. Requires an `onChange` handler to update the state.

Uncontrolled Components

The DOM itself manages the state of the form element. React accesses the value through a `ref`. The component doesn't re-render when the input value changes.

Step by step

Controlled Components - Advantages:

  • Single Source of Truth: React state controls the form, making data flow predictable.
  • Validation: Easier to perform validation and enforce rules dynamically.
  • Integration: Works seamlessly with React's state and lifecycle methods.

Controlled Components - Disadvantages:

  • Verbose Code: Requires additional state and handlers for every input.
  • Performance: Frequent re-renders may impact performance for large forms.

Uncontrolled Components - Advantages:

  • Simpler Code: No need to manage state or handlers for inputs.
  • Performance: Fewer re-renders, as the input state is not managed by React.
  • Use Cases: Ideal for simple forms or when integrating with non-React libraries.

Uncontrolled Components - Disadvantages:

  • Validation: Harder to validate and enforce rules dynamically.
  • Limited React Control: React has less control over the form element's behavior.
  • Debugging: Accessing and managing refs can make debugging harder.

When to Use Controlled Components:

  • Complex forms with real-time validation.
  • When the form data needs to be synchronized with React state.
  • Dynamic forms where input values affect other parts of the UI.

When to Use Uncontrolled Components:

  • Simple forms where React doesn't need to manage input values.
  • Forms where performance is critical, and re-renders need to be minimized.
  • When integrating with non-React libraries that rely on direct DOM manipulation.

Examples

Controlled Component Example:

import React, { useState } from 'react';

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

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

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(`Submitted Value: ${inputValue}`);
  };

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

Uncontrolled Component Example:

import React, { useRef } from 'react';

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

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(`Submitted Value: ${inputRef.current.value}`);
  };

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

Mixing Controlled and Uncontrolled Components:

import React, { useState, useRef } from 'react';

function MixedForm() {
  const [email, setEmail] = useState('');
  const nameRef = useRef(null);

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(`Name: ${nameRef.current.value}, Email: ${email}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name (Uncontrolled):
        <input type="text" ref={nameRef} />
      </label>
      <label>
        Email (Controlled):
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus