A controlled component is a form element (like input, textarea, select) whose value is controlled by React state. The component's displayed value is set by React, and user input updates the state.
Click to reveal answer
beginner
How do you update the value of a controlled input in React?
You update the value by changing the state that controls the input's value, usually inside an event handler like onChange.
Click to reveal answer
intermediate
Why are controlled components preferred over uncontrolled components in React?
Controlled components keep React as the single source of truth for form data, making it easier to validate, modify, or submit form data and keep UI consistent.
Click to reveal answer
intermediate
What happens if you do not provide an onChange handler to a controlled input?
The input becomes read-only because React controls its value but has no way to update it from user input.
D. The onChange handler does not call setName with the new value
Solution
Step 1: Check onChange handler usage
The onChange handler is set to 'e => setName' which is a function reference, not a call with the new value.
Step 2: Correct onChange handler
It should be 'e => setName(e.target.value)' to update state with input value.
Final Answer:
The onChange handler does not call setName with the new value -> Option D
Quick Check:
onChange must call setState with event value [OK]
Hint: onChange must call setState with event target value [OK]
Common Mistakes:
Passing setName without calling it
Using defaultValue instead of value in controlled input
Forgetting to pass initial state to useState
5. You want to create a controlled textarea that converts all input to uppercase as the user types. Which code snippet correctly implements this?
hard
A. const [text, setText] = React.useState('');
return
B. const [text, setText] = React.useState('');
return
C. const [text, setText] = React.useState('');
return
D. const [text, setText] = React.useState('');
return
Solution
Step 1: Understand controlled textarea with uppercase transformation
The textarea's value must come from state, and onChange must update state with uppercase input.
Step 2: Analyze each option
const [text, setText] = React.useState('');
return <textarea value={text} onChange={e => setText(e.target.value.toUpperCase())} />; updates state with uppercase input on change and sets value from state, so textarea shows uppercase as typed.