Complete the code to update state using a callback function.
const [count, setCount] = useState(0); function increment() { setCount([1]); }
Using a callback function with setCount ensures you get the latest state value when updating.
Complete the code to toggle a boolean state using a callback function.
const [isOn, setIsOn] = useState(false);
function toggle() {
setIsOn([1]);
}The callback function receives the previous state and returns its opposite, toggling the boolean correctly.
Fix the error in updating a counter state multiple times in a row.
const [counter, setCounter] = useState(0); function increaseTwice() { setCounter([1]); setCounter([1]); }
Using the callback form ensures each update uses the latest state, so calling twice increments by two.
Fill both blanks to update state with a callback and log the new value.
const [value, setValue] = useState(0); function updateAndLog() { setValue([1]); console.log([2]); }
Use a callback to update state safely, and log the current state variable (which is still the old value immediately after setState).
Fill all three blanks to update a list state by adding a new item using a callback.
const [items, setItems] = useState([]);
function addItem(newItem) {
setItems([1] => [...[2], [3]]);
}The callback receives previous items, spreads them into a new array, and adds the new item at the end.