0

How do controlled and uncontrolled components differ in React?

author
subina kallyani
easy
0
0

Answer

In React, controlled and uncontrolled components describe how form data is handled.

The main difference is where the form state is managed.


Controlled Components

In a controlled component, form input values are fully managed by React state.

  • Input value comes from state
  • Updates happen using onChange
  • React has full control over the data

Example:

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

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


Uncontrolled Components

In an uncontrolled component, form values are managed by the DOM itself, not React state.

  • Uses ref to access values
  • Less code, but less control
  • React doesn’t track input changes

Example:

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

return <input ref={inputRef} />;
}

Click to Reveal Answer

Tap anywhere to see the solution

Revealed

Comments0