← React Beginner Questions - Set 2 Q12

What is the difference between a controlled and an uncontrolled component?

React Beginner Questions - Set 2

One input, two philosophies: React owns the value, or the DOM owns it and you read it on demand.

Example

import { useState, useRef } from 'react';

export default function Form() {
  const [controlled, setControlled] = useState('');
  const uncontrolledRef = useRef(null);

  function submit(e) {
    e.preventDefault();
    console.log('controlled  :', controlled);
    console.log('uncontrolled:', uncontrolledRef.current.value);
  }

  return (
    <form onSubmit={submit}>
      <input value={controlled} onChange={e => setControlled(e.target.value)} />
      <input defaultValue="initial" ref={uncontrolledRef} />
      <button type="submit">Send</button>
    </form>
  );
}

What to notice

← Back to the question list