Controlled vs uncontrolled input?
Practice this questionWANT TO UNDERSTAND THE CONCEPT FIRST?Learn Controlled vs uncontrolled input?
Definition:
A controlled input takes its displayed value from React state, with changes flowing through an event handler. An uncontrolled input keeps its current value in the DOM until the application reads it. Controlled inputs make coordinated validation and UI changes convenient, while uncontrolled inputs can keep simple forms less state-heavy.
Key points:
-
Controlled: React state supplies the value, updated through an event handler.
-
Uncontrolled: the DOM keeps the value; read it through a ref or form submission.
-
Validate on the server too; browser checks can be bypassed.
-
Do not switch the same input unexpectedly from an undefined value to a controlled string value; initialize it consistently.
Example — controlled input:
import { useState } from 'react';
function NameInput() {
const [name, setName] = useState('');
return (
<input
aria-label="Name"
value={name}
onChange={event => setName(event.target.value)}
/>
);
}- The event updates state; the next render supplies the input's displayed value.
Interview point:
- Choose based on how much the UI must react to each change, and validate submitted values on the server regardless.
Adapted from 06_REACT_NEXTJS.md · “Controlled vs uncontrolled input?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.