Controlled vs. Uncontrolled Components

In React, form elements can be either controlled or uncontrolled, depending on how the form state is managed.

🧠 Controlled Components:

  • In controlled components, the state of the form element is managed by React via the component's state.

  • React updates the state when the user interacts with the form element (e.g., typing in a text field).

  • Example:

javascript
1const MyForm = () => { 2 const [value, setValue] = useState(''); 3 4 const handleChange = (e) => { 5 setValue(e.target.value); 6 }; 7 8 return <input value={value} onChange={handleChange} />; 9}

🧠 Uncontrolled Components:

  • In uncontrolled components, form state is managed by the DOM, typically using a ref.

  • React doesn’t directly manage the state of the form element.

Example:

javascript
1const MyForm = () => { 2 const inputRef = useRef(); 3 4 const handleSubmit = () => { 5 console.log(inputRef.current.value); 6 }; 7 8 return <input ref={inputRef} />; 9}

In short:

  • Controlled components have their state managed by React, while uncontrolled components let the DOM manage the form state.