SmartCodingTips

πŸŽ›οΈ Controlled vs Uncontrolled Components

In React, form inputs can be either controlled or uncontrolled. Understanding the difference is key to building reliable and scalable forms.


βœ… Controlled Components

Controlled components have their state fully managed by React. Input values are linked to state variables, and changes are handled through events.


function ControlledInput() {
  const [name, setName] = React.useState("");

  const handleChange = (e) => setName(e.target.value);

  return (
    <input type="text" value={name} onChange={handleChange} />
  );
}
  • βœ… React has full control of the value
  • βœ… Enables validation, conditional logic, etc.
  • ⚠️ Requires more code and state management

πŸ•ΉοΈ Uncontrolled Components

Uncontrolled components rely on the DOM to manage their values using a ref. React doesn’t track the input's state directly.


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

  const handleSubmit = () => {
    alert("Input value: " + inputRef.current.value);
  };

  return (
    <>
      <input type="text" ref={inputRef} />
      <button onClick={handleSubmit}>Submit</button>
    </>
  );
}
  • βœ… Less code, simpler in small forms
  • ⚠️ Harder to validate or manipulate programmatically
  • ⚠️ Doesn’t reflect state in React’s data flow

πŸ“‹ When to Use Each

  • Use Controlled: When you need validation, conditional logic, or dynamic updates.
  • Use Uncontrolled: For simple forms or when integrating with non-React libraries.
Aspect Controlled Uncontrolled
State Managed by React Managed by DOM
Validation Easier Harder
Code Complexity Higher Lower
Refs Required No Yes

Controlled components are the preferred approach in React apps due to their flexibility and integration with the React state model. Uncontrolled components can be useful in isolated, simple use cases.