Script Valley
React.js: Complete Course
State and Event HandlingLesson 2.3

Controlled vs uncontrolled components in React forms

controlled inputs, uncontrolled inputs, useRef for uncontrolled, two-way binding pattern, form state management, when to use each approach

Controlled vs Uncontrolled Inputs

In a controlled input, React state drives the input value. In an uncontrolled input, the DOM manages its own value and you read it with a ref. Controlled is the React-idiomatic approach for most forms.

Controlled Input

import { useState } from 'react';

function LoginForm() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  function handleSubmit(e) {
    e.preventDefault();
    console.log({ email, password });
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={e => setEmail(e.target.value)}
      />
      <input
        type="password"
        value={password}
        onChange={e => setPassword(e.target.value)}
      />
      <button>Login</button>
    </form>
  );
}

Uncontrolled Input with useRef

import { useRef } from 'react';

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

  function handleSearch() {
    console.log(inputRef.current.value);
  }

  return (
    <>
      <input ref={inputRef} type="text" />
      <button onClick={handleSearch}>Search</button>
    </>
  );
}

Use controlled inputs when you need real-time validation, conditional rendering, or to sync with other state. Use uncontrolled inputs for simple read-once scenarios like file uploads or integrating with non-React code.

Up next

Lifting state up in React component trees

Sign in to track progress

Controlled vs uncontrolled components in React forms โ€” State and Event Handling โ€” React.js: Complete Course โ€” Script Valley โ€” Script Valley