Controlled & Uncontrolled Components

Med

Controlled components have their form values managed by React state, making React the single source of truth. Uncontrolled components let the DOM manage the value, accessed via refs. Understanding when to use each approach is important for building forms effectively.

Interactive Visualization

Key Points

  • Controlled: value prop + onChange handler, React state is the source of truth
  • Uncontrolled: defaultValue + ref, DOM is the source of truth
  • Controlled gives full programmatic control for validation, formatting, and conditional logic
  • Uncontrolled is simpler for basic forms where you only need the value on submit
  • Setting value without onChange creates a read-only input that React warns about
  • File inputs are always uncontrolled because their value is read-only for security

Code Examples

Controlled vs Uncontrolled

import { useState, useRef, type FormEvent } from 'react'

function ControlledForm() {
  const [email, setEmail] = useState('')
  const [error, setError] = useState('')

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value
    setEmail(value)
    setError(value.includes('@') ? '' : 'Invalid email')
  }

  return (
    <div>
      <input value={email} onChange={handleChange} />
      {error && <span>{error}</span>}
    </div>
  )
}

function UncontrolledForm() {
  const emailRef = useRef<HTMLInputElement>(null)

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault()
    const value = emailRef.current?.value ?? ''
    // Validate only on submit
  }

  return (
    <form onSubmit={handleSubmit}>
      <input ref={emailRef} defaultValue="" />
      <button type="submit">Submit</button>
    </form>
  )
}

Controlled components validate on every keystroke while uncontrolled components read the value only when needed

Common Mistakes

  • Providing value without onChange, creating a frozen input that cannot be typed into
  • Switching between controlled and uncontrolled by toggling between value and defaultValue
  • Trying to control file inputs which are always uncontrolled for security reasons

Interview Tips

  • Explain the trade-off: controlled gives more power but more boilerplate
  • Discuss when uncontrolled is actually the better choice like simple search forms
  • Know that React warns when switching between controlled and uncontrolled modes

Related Concepts