All quizzesMedium
Component Patterns — Series 3
Preview — 3 of 10 questions
React logs: A component is changing an uncontrolled input to be controlled. What caused it?
javascript
function NameField() {
const [name, setName] = useState();
return <input value={name} onChange={(e) => setName(e.target.value)} />;
}AuseState() with no argument makes name start as undefined, so value={undefined} renders an uncontrolled input on the first render; once the user types, name becomes a string and the input flips to controlled. Initialize the state to '' so it is controlled from the start
BonChange should be onInput for text fields
Cvalue cannot be used together with onChange
DThe input needs a name attribute
Which update is correct?
javascript
const [form, setForm] = useState({ user: { name: 'Ada', address: { city: 'London' } } });
function setCity(city) {
// update form.user.address.city immutably
}Aform.user.address.city = city; setForm(form);
BsetForm({ ...form, city });
CsetForm({ ...form, user: { ...form.user, address: { ...form.user.address, city } } });
DsetForm({ user: { address: { city } } });
ProfileForm holds local draft state in useState. When userId changes, what happens, and why choose this over a useEffect?
javascript
<ProfileForm key={userId} user={user} />ANothing — key on a component is ignored unless it is inside .map()
BChanging key makes React unmount the old ProfileForm and mount a fresh one, so all its internal state resets to initial values for the new user. This is simpler and less bug-prone than a useEffect that watches userId and manually resets each piece of state
Ckey change only re-runs effects, not state
DIt throws because key must be a string
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.