Dung (Donny) Nguyen

Senior Software Engineer

Controlled and Uncontrolled Components

In React.js, the difference between controlled and uncontrolled components revolves around how they handle form data and manage state.

Controlled Components

Definition: Controlled components are those in which form data is handled by the React component itself. The component’s state is the single source of truth, and the state is updated via event handlers.

Characteristics:

Example:

import React, { useState } from 'react';

function ControlledComponent() {
  const [value, setValue] = useState('');

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

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

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

export default ControlledComponent;

In this example, the value of the input field is controlled by the component’s state, and it updates via the handleChange event handler.

Uncontrolled Components

Definition: Uncontrolled components are those in which form data is handled by the DOM itself. We access the form data using references (refs) instead of managing state within the component.

Characteristics:

Example:

import React, { useRef } from 'react';

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

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

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

export default UncontrolledComponent;

In this example, the value of the input field is accessed through a reference (ref) instead of being managed by the component’s state.

Key Differences

Choosing between controlled and uncontrolled components depends on the complexity of our form and the level of control we need over our form data. If we need precise control and robust handling, controlled components are the way to go. For simpler needs or quick implementations, uncontrolled components can be an efficient choice.