Sobes.tech
Middle

What is the difference between a controlled and uncontrolled component in React?

sobes.tech AI

Answer from AI

A controlled component in React is a component whose (for example, input value) state is fully managed through React's props and state. The form element's value is stored in the component's state, and any changes are handled through event handlers that update the state.

An uncontrolled component is a component that keeps its state within the DOM, not in React state. Access to the value is done directly through the DOM via ref.

Example of a controlled component:

function ControlledInput() {
  const [value, setValue] = React.useState('');

  return (
    <input
      value={value}
      onChange={e => setValue(e.target.value)}
    />
  );
}

Example of an uncontrolled component:

function UncontrolledInput() {
  const inputRef = React.useRef(null);

  const handleClick = () => {
    alert(inputRef.current.value);
  };

  return (
    <>
      <input ref={inputRef} defaultValue="" />
      <button onClick={handleClick}>Show value</button>
    </>
  );
}

Controlled components give full control over the state and are convenient for validation and complex logic, while uncontrolled components are simpler and closer to regular HTML.

What is the difference between a controlled and… - sobes.tech