0
0
Reactframework~10 mins

Callback functions for state updates in React - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to update state using a callback function.

React
const [count, setCount] = useState(0);

function increment() {
  setCount([1]);
}
Drag options to blanks, or click blank then click option'
Aprev => prev + 1
Bcount + 1
Ccount++
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using the current state variable directly can cause stale updates.
Trying to increment with 'count++' does not work in React state updates.
2fill in blank
medium

Complete the code to toggle a boolean state using a callback function.

React
const [isOn, setIsOn] = useState(false);

function toggle() {
  setIsOn([1]);
}
Drag options to blanks, or click blank then click option'
AisOn = !isOn
Btrue
Cprev => !prev
D!isOn
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!isOn' directly can cause issues if state updates are batched.
Trying to assign a new value to 'isOn' directly is not allowed.
3fill in blank
hard

Fix the error in updating a counter state multiple times in a row.

React
const [counter, setCounter] = useState(0);

function increaseTwice() {
  setCounter([1]);
  setCounter([1]);
}
Drag options to blanks, or click blank then click option'
Acounter + 1
Bprev => prev + 1
Ccounter++
Dcounter += 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'counter + 1' twice only increments once due to stale state.
Trying to increment with 'counter++' or 'counter += 1' causes errors.
4fill in blank
hard

Fill both blanks to update state with a callback and log the new value.

React
const [value, setValue] = useState(0);

function updateAndLog() {
  setValue([1]);
  console.log([2]);
}
Drag options to blanks, or click blank then click option'
Aprev => prev + 5
Bvalue
Cprev + 5
Dvalue + 5
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to log the updated state immediately after setState shows old value.
Using 'prev + 5' directly without a function causes errors.
5fill in blank
hard

Fill all three blanks to update a list state by adding a new item using a callback.

React
const [items, setItems] = useState([]);

function addItem(newItem) {
  setItems([1] => [...[2], [3]]);
}
Drag options to blanks, or click blank then click option'
AprevItems
CnewItem
Ditems
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'items' directly instead of previous state can cause stale updates.
Not spreading previous items results in overwriting the list.