ESC

Type to search the knowledge base.

Forms in React

Controlled vs uncontrolled inputs, form state, validation UX, and when native form submit is enough.

beginner4 min read
  • react
  • forms-in

Forms are where React state meets user intent. The core choice is controlled (React state is the source of truth for field values) versus uncontrolled (the DOM holds values until you read them). Most app UIs want controlled fields for validation and conditional UI; simple progressive-enhancement forms can stay closer to HTML.

Docs: Reacting to Input with State, <input>.

Controlled input

function LoginForm({ onSubmit }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState(null);

  function handleSubmit(e) {
    e.preventDefault();
    if (!email.includes('@')) {
      setError('Enter a valid email');
      return;
    }
    setError(null);
    onSubmit({ email, password });
  }

  return (
    <form onSubmit={handleSubmit} noValidate>
      <label htmlFor="email">Email</label>
      <input
        id="email"
        name="email"
        type="email"
        autoComplete="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <label htmlFor="password">Password</label>
      <input
        id="password"
        name="password"
        type="password"
        autoComplete="current-password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      {error && <p role="alert">{error}</p>}
      <button type="submit">Sign in</button>
    </form>
  );
}

Always pair label + id. Surface errors with role="alert" or aria-describedby. See useId for stable ids in reusable fields.

Uncontrolled + FormData

function SearchBox({ onSearch }) {
  function handleSubmit(e) {
    e.preventDefault();
    const data = new FormData(e.currentTarget);
    onSearch(String(data.get('q') ?? ''));
  }
  return (
    <form onSubmit={handleSubmit}>
      <input name="q" defaultValue="" aria-label="Search" />
      <button type="submit">Go</button>
    </form>
  );
}

defaultValue sets initial DOM state; React does not drive each keystroke. Good for large free-text areas when you do not need per-keystroke React logic.

Object state for many fields

const [form, setForm] = useState({ name: '', company: '', role: '' });
const setField = (key) => (e) =>
  setForm((f) => ({ ...f, [key]: e.target.value }));

Or useReducer when transitions include async submit states. Avoid derived state copies of server entities without a draft model.

Libraries and server actions

React Hook Form, Conform, and similar tools reduce re-renders and wire schema validation. In Next.js, Server Actions can receive FormData directly from progressive forms — still validate on the server.

Interview out-loud

“Controlled inputs keep value in React state for validation and conditional UI. Uncontrolled inputs use the DOM and FormData for simpler cases. I preventDefault on submit, associate labels, announce errors accessibly, and keep one source of truth for each field.”

Further reading

Edge cases worth rehearsing

Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.

Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.

When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.

Edge cases worth rehearsing

Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.

Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.

When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.

Related guides