Complete the code to update the state using the setter function.
const [count, setCount] = useState(0); function increment() { setCount([1]); }
To increase the count by one, you add 1 to the current count and pass it to setCount.
Complete the code to update state based on the previous state value.
const [likes, setLikes] = useState(0); function addLike() { setLikes([1] => [1] + 1); }
When updating state based on previous state, use a function with a parameter representing the previous value, commonly named prev.
Fix the error in the state update to correctly toggle a boolean value.
const [isOn, setIsOn] = useState(false);
function toggle() {
setIsOn([1] => ![1]);
}To toggle a boolean state, use the previous state parameter (commonly prev) and return its negation.
Fill both blanks to update an object state property correctly.
const [user, setUser] = useState({ name: 'Alice', age: 25 });
function updateName(newName) {
setUser({ ...user, [1]: [2] });
}To update the name property in the user object, spread the existing user and set name to newName.
Fill both blanks to update a nested state object immutably.
const [profile, setProfile] = useState({
user: { name: 'Bob', details: { age: 30, city: 'NY' } }
});
function updateCity(newCity) {
setProfile({
...profile,
user: {
...profile.user,
details: { ...profile.user.details, [1]: [2] }
}
});
}To update the nested city property, spread the outer objects and set city to newCity. The age option is a distractor here and not used in the code.