Q1. What are controlled components in React?
Controlled components are form elements whose value is controlled by React state.
The input's value prop is set to a state variable, and onChange updates that variable.
This gives React full control over the input, enabling features like instant validation.
The input's value prop is set to a state variable, and onChange updates that variable.
This gives React full control over the input, enabling features like instant validation.
Q2. How do you create a controlled input?
Example:
const [name, setName] = useState('');
return <input type="text" value={name} onChange={(e) => setName(e.target.value)} />;
The input displays the state and updates it on every keystroke.Q3. What about checkboxes and radio buttons?
For checkboxes, use
Radio buttons work similarly with
checked prop instead of value: <input type="checkbox" checked={isChecked} onChange={(e) => setIsChecked(e.target.checked)} />.Radio buttons work similarly with
checked and value.Q4. What are the benefits of controlled components?
They provide a single source of truth, make form state predictable, and allow immediate feedback (validation, formatting).
They also integrate easily with other React features like conditional rendering.
They also integrate easily with other React features like conditional rendering.
Q5. What is a potential downside?
For very large forms, controlled components can cause many re-renders (on each keystroke).
This can be optimized with debouncing or using uncontrolled components with refs for performance-critical scenarios.
This can be optimized with debouncing or using uncontrolled components with refs for performance-critical scenarios.
