JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
PrevNext
react
mid
forms

What is the difference between controlled and uncontrolled components in React forms?

forms
controlled
uncontrolled
inputs
refs
Quick Answer

Controlled components have their form data managed by React state - the input value is always driven by state. Uncontrolled components let the DOM handle form data using refs to access values when needed. Controlled components are recommended for most cases.

Detailed Explanation

Controlled Components:

  • React state is the 'single source of truth'
  • Every state mutation has an associated handler
  • Input value always reflects state
  • Form data is instantly accessible
  • Enables validation, conditional disabling, enforced formats

Uncontrolled Components:

  • DOM maintains its own state
  • Use refs to access values
  • Like traditional HTML forms
  • Less code for simple cases
  • Useful for integrating non-React code

When to Use Each:

  • Controlled: Most forms, validation, instant feedback
  • Uncontrolled: Simple forms, file inputs, third-party integrations

Code Examples

Controlled component
function ControlledForm() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    agree: false
  });
  const [errors, setErrors] = useState({});
  
  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
  };
  
  const validate = () => {
    const newErrors = {};
    if (!formData.name) newErrors.name = 'Name required';
    if (!formData.email.includes('@')) newErrors.email = 'Invalid email';
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  
  const handleSubmit = (e) => {
    e.preventDefault();
    if (validate()) {
      console.log('Submit:', formData);
    }
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <input
        name="name"
        value={formData.name}
        onChange={handleChange}
      />
      {errors.name && <span>{errors.name}</span>}
      
      <input
        name="email"
        value={formData.email}
        onChange={handleChange}
      />
      
      <input
        type="checkbox"
        name="agree"
        checked={formData.agree}
        onChange={handleChange}
      />
      
      <button disabled={!formData.agree}>Submit</button>
    </form>
  );
}

Resources

React Docs - Reacting to Input with State

docs

Formik - Form Library

docs

Related Questions

What is useRef and when should you use it?

mid
hooks

Explain the useState and useEffect hooks and their common patterns.

mid
hooks
Previous
What is useRef and when should you use it?
Next
How does React Router work and what are its key features?