← Back to Chapters

Controlled vs Uncontrolled Inputs

? Controlled vs Uncontrolled Inputs

? Quick Overview

In React, form inputs can be managed in two ways — as controlled or uncontrolled components. Choosing the right approach helps you build predictable and maintainable forms.

? Key Concepts

  • Controlled inputs store data in React state
  • Uncontrolled inputs store data in the DOM
  • Controlled inputs re-render on every change
  • Uncontrolled inputs are accessed only when needed

? Controlled Components

A controlled component uses useState() to manage the value of an input. React becomes the single source of truth for the form data.

? View Code Example
// Controlled input managed fully by React state
import React, { useState } from "react";

function ControlledInput() {
const [name, setName] = useState("");

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

const handleSubmit = (e) => {
e.preventDefault();
alert("Submitted Name: " + name);
};

return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
onChange={handleChange}
placeholder="Enter your name"
/>
<button>Submit</button>
</form>
);
}

export default ControlledInput;

Here, React controls the input value, keeping UI and state perfectly in sync.

? Uncontrolled Components

An uncontrolled component lets the DOM handle input data. You access the value only when required using useRef().

? View Code Example
// Uncontrolled input accessed directly from the DOM
import React, { useRef } from "react";

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

const handleSubmit = (e) => {
e.preventDefault();
alert("Submitted Name: " + inputRef.current.value);
};

return (
<form onSubmit={handleSubmit}>
<input
type="text"
ref={inputRef}
placeholder="Enter your name"
/>
<button>Submit</button>
</form>
);
}

export default UncontrolledInput;

The DOM stores the value internally, and React reads it only when submitting.

⚖️ Comparison Summary

  • Controlled: Best for complex forms and validation
  • Uncontrolled: Best for simple or quick data capture
  • Never mix both patterns on the same input

? Tips & Best Practices

  • Prefer controlled inputs for dynamic or validated forms
  • Use uncontrolled inputs for simple, performance-friendly forms
  • Always choose one pattern per input
  • Initialize controlled state to avoid warnings

? Try It Yourself

  1. Create a controlled login form with live validation
  2. Build an uncontrolled feedback form using useRef()
  3. Compare re-render behavior between both approaches

Goal: Learn when and why to use each input management strategy.