Step 1: Understand state updates are asynchronous and batched
Both setCount(count + 1) calls use the same count value (0) because state updates are batched.
Step 2: Result after both calls
Both calls set count to 1, so after clicking, count becomes 1, not 2.
Final Answer:
1 -> Option D
Quick Check:
Multiple setState with same value = C [OK]
Hint: Multiple setState calls with same value batch to last one [OK]
Common Mistakes:
Assuming count increments twice immediately
Expecting count to be 2 after two calls
Ignoring React's batching behavior
4. Identify the error in the following React component that tries to update state on button click:
import React, { useState } from 'react';
function Toggle() {
const [isOn, setIsOn] = useState(false);
function handleClick() {
isOn = !isOn;
}
return {isOn ? 'ON' : 'OFF'};
}
medium
A. Button missing onClick handler.
B. Directly assigning to state variable instead of using setter.
C. Using incorrect initial state value.
D. Missing parentheses in function declaration.
Solution
Step 1: Check how state is updated
The code tries to assign isOn = !isOn; directly, which is not allowed for state variables.
Step 2: Correct way to update state
State must be updated by calling the setter function: setIsOn(!isOn);.
Final Answer:
Directly assigning to state variable instead of using setter. -> Option B
Quick Check:
Update state only via setter function = D [OK]
Hint: Never assign state variable directly; always use setter [OK]
Common Mistakes:
Assigning state variable directly
Forgetting to call setter function
Confusing state variable with setter
5. You want to update a state object user with a new age property without losing other properties. Which is the correct way to update state using setUser?
const [user, setUser] = useState({ name: 'Alice', age: 25 });
// Update age to 26
hard
A. setUser(prevUser => ({ ...prevUser, age: 26 }));
B. setUser({ age: 26 });
C. setUser(user.age = 26);
D. setUser(prevUser => { prevUser.age = 26 });
Solution
Step 1: Preserve existing properties when updating state object
To update one property without losing others, copy previous state using spread syntax.
Step 2: Use functional update form to get latest state
Use setUser(prevUser => ({ ...prevUser, age: 26 })) to merge old properties with new age.
Final Answer:
setUser(prevUser => ({ ...prevUser, age: 26 })); -> Option A
Quick Check:
Use spread and functional update to merge state = A [OK]
Hint: Use spread operator and functional setter to update object state [OK]
Common Mistakes:
Replacing whole object losing other properties
Mutating state directly instead of returning new object
Not using functional update when depending on previous state
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.