Skip to content

Controlled and Uncontrolled Components in React

In React, components can be classified as controlled or uncontrolled based on how they manage their state and data.

Controlled Components

Controlled components are those where the state is managed by React.

The component’s value is controlled by React’s state, and changes are handled via event handlers.

import React, { useState } from 'react';

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

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

  return (
    <input
      type="text"
      value={value}
      onChange={handleChange}
    />
  );
}

Uncontrolled Components

Uncontrolled components are those where the state is managed by the DOM itself, and React does not control the component’s value.

Instead, you use refs to access the DOM element directly.

import React, { useRef } from 'react';

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

  const handleSubmit = () => {
    alert('Input value: ' + inputRef.current.value);
  };

  return (
    <div>
      <input type="text" ref={inputRef} />
      <button onClick={handleSubmit}>Submit</button>
    </div>
  );
}

Key Differences

FeatureControlled ComponentsUncontrolled Components
State ManagementManaged by React stateManaged by the DOM
Data AccessAccessed via stateAccessed via refs
Use CaseForms, dynamic inputsSimple inputs, file uploads
PerformanceSlightly slower (due to re-renders)Faster (no re-renders)

Summary

Both controlled and uncontrolled components have their place in React development. Understanding their differences helps you write more efficient, maintainable, and scalable applications.

For most cases, controlled components are recommended due to their predictability, but if performance is a key factor, uncontrolled components may be the better choice.