Sobes.tech
Middle

What is the difference between controlled and uncontrolled input, and when should each be used?

sobes.tech AI

Answer from AI

Controlled input — is a form element whose value is fully controlled by the component's state (for example, in React). The field's value is stored in the state and updated via an event handler.

Uncontrolled input — is a form element that is managed by the DOM itself, not the component's state. The value is read through refs when needed.

When to use:

  • Controlled input is convenient when you need to react immediately to changes, validate data, or synchronize with the application's state.
  • Uncontrolled input is simpler and faster for simple forms where constant control over input is not required.

Example of a controlled input in React:

function MyInput() {
  const [value, setValue] = React.useState('');
  return <input value={value} onChange={e => setValue(e.target.value)} />;
}

Example of an uncontrolled input:

function MyInput() {
  const inputRef = React.useRef(null);
  const handleSubmit = () => {
    alert(inputRef.current.value);
  };
  return <>
    <input ref={inputRef} />
    <button onClick={handleSubmit}>Submit</button>
  </>;
}
What is the difference between controlled and… - sobes.tech