Controlled vs Uncontrolled Components
⚛ ری‌اکت

Controlled vs Uncontrolled Components

Who owns form state — React or the DOM? A fundamental pattern for forms and file inputs.

BugCast Admin··۵ دقیقه مطالعه

Controlled components store form values in React state; uncontrolled components read from the DOM via refs. Interviewers ask when to pick each approach.

Common Interview Questions

Q: What is a controlled input?

Answer: React state is the single source of truth. Every keystroke updates state, which re-renders the input with the new value.


const [email, setEmail] = useState("");
return (
  <input value={email} onChange={(e) => setEmail(e.target.value)} />
);

Q: What is an uncontrolled input?

Answer: The DOM holds the value. Read it on submit with ref.current.value. Use defaultValue/defaultChecked, not value, for initial state.


const ref = useRef(null);
return <input ref={ref} defaultValue="hello" />;

Q: When prefer uncontrolled?

Answer: Simple forms, file inputs (always uncontrolled), integrating non-React widgets, or when you do not need live validation on every keystroke.

Q: Common controlled input bug?

Answer: Setting value={state} without onChange makes the input read-only and logs warnings. Either add onChange or use defaultValue for uncontrolled.

Key Points for Interviews

  • Controlled = React state drives value

  • Uncontrolled = ref reads DOM on demand

  • File inputs cannot be controlled via value

  • Libraries like React Hook Form blend both patterns

  • Controlled enables instant validation and formatting

#forms#controlled#interview

مطالب مرتبط