Question Bank
/

React Controlled vs Uncontrolled Components: Two Explanations Quiz

React Controlled vs Uncontrolled Components: Two Explanations Quiz

Two explanations of controlled vs uncontrolled inputs with concrete code, plus companions on `defaultValue` and on extending the controlled idea beyond form inputs.

Question Bank
Easy
JavaScript
4 questions
quiz
react
hooks
js-dom

977 views

16

Define a controlled input and an uncontrolled input in React, and explain who owns the source of truth for the value in each case.

Examples

Example 1:

Input: a text field that the parent component reads on every keystroke
Output: controlled (value comes from React state, parent sees every change via onChange)
Explanation: React holds the state; the DOM is a downstream view.

Example 2:

Input: a text field that the parent only inspects when the form is submitted
Output: uncontrolled (the DOM owns the value; React reads it via a ref)
Explanation: the input keeps its own state internally; React queries it on demand.
import { useRef, useState } from 'react';

// controlled: React state is the source of truth
function ControlledName() {
    const [name, setName] = useState('');
    return <input value={name} onChange={(e) => setName(e.target.value)} />;
}

// uncontrolled: the DOM is the source of truth
function UncontrolledName() {
    const ref = useRef(null);
    const submit = () => console.log(ref.current.value);
    return (
        <>
            <input ref={ref} defaultValue="" />
            <button onClick={submit}>submit</button>
        </>
    );
}