Callback functions help update state based on the previous state safely. They avoid mistakes when many updates happen quickly.
Callback functions for state updates in React
Introduction
Syntax
React
setState(prevState => newState)
The callback receives the previous state as an argument.
Return the new state from the callback.
Examples
React
setCount(prevCount => prevCount + 1)React
setIsOpen(prevIsOpen => !prevIsOpen)
React
setItems(prevItems => [...prevItems, newItem])
Sample Program
This component shows a number starting at 0. When you click the button, it uses a callback function to add 1 to the current count safely.
React
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); function handleClick() { setCount(prevCount => prevCount + 1); } return ( <div> <p>Count: {count}</p> <button onClick={handleClick} aria-label="Increase count">Increase</button> </div> ); } export default Counter;
Important Notes
Always use callback functions when new state depends on old state to avoid bugs.
React batches state updates, so direct state reads may be outdated inside event handlers.
Callback functions help React update state in the right order.
Summary
Callback functions receive previous state and return new state.
Use them when new state depends on old state.
They keep state updates safe and predictable.
Practice
1. Why should you use a callback function when updating state in React with
useState?easy
Solution
Step 1: Understand state updates in React
State updates can be asynchronous, so relying on the current state value directly can cause bugs.Step 2: Use callback function to access previous state
The callback function receives the previous state safely and returns the new state, ensuring correct updates.Final Answer:
Because it safely uses the previous state value to calculate the new state. -> Option AQuick Check:
Callback uses previous state = safe update [OK]
Hint: Use callback to get previous state safely for updates [OK]
Common Mistakes:
- Updating state directly without callback causes stale values
- Thinking callback triggers extra renders
- Believing callback merges multiple states automatically
2. Which of the following is the correct syntax to update state using a callback function with
useState?easy
Solution
Step 1: Identify correct callback syntax
The callback function receives previous state as an argument and returns the new state.Step 2: Check each option
setCount(prevCount => prevCount + 1); usesprevCount => prevCount + 1, which is the correct callback form.Final Answer:
setCount(prevCount => prevCount + 1); -> Option BQuick Check:
Callback syntax = setState(prev => new) [OK]
Hint: Callback syntax always uses previous state parameter [OK]
Common Mistakes:
- Passing new state directly without function
- Using arrow function without parameter
- Trying to add number outside callback
3. What will be the output after clicking the button twice in this React component?
function Counter() {
const [count, setCount] = React.useState(0);
function increment() {
setCount(prev => prev + 1);
}
return (
<button onClick={increment}>Count: {count}</button>
);
}medium
Solution
Step 1: Understand initial state and increment function
Initial count is 0. Each click callsincrementwhich updates state by adding 1 to previous count.Step 2: Calculate state after two clicks
First click: 0 + 1 = 1. Second click: 1 + 1 = 2.Final Answer:
Count: 2 -> Option AQuick Check:
Two increments = count 2 [OK]
Hint: Each click adds 1 to previous count using callback [OK]
Common Mistakes:
- Assuming state updates are batched incorrectly
- Using stale count value without callback
- Expecting count to reset after each click
4. Identify the error in this React state update code:
const [value, setValue] = React.useState(0);
function update() {
setValue(value + 1);
setValue(value + 1);
}medium
Solution
Step 1: Analyze multiple state updates with direct value
Both calls use the same stalevalue(0), so both set to 1.Step 2: Understand batching behavior
React batches updates, so final state is 1, not 2.Final Answer:
State updates will be batched and only increase by 1, not 2. -> Option CQuick Check:
Direct state updates = stale value, batched result [OK]
Hint: Multiple direct updates use stale state, use callback instead [OK]
Common Mistakes:
- Thinking setValue calls add up automatically
- Believing syntax error occurs without callback
- Assuming state resets unexpectedly
5. You want to toggle a boolean state
isOpen in React. Which is the best way to update it safely when the new state depends on the old state?hard
Solution
Step 1: Understand toggling boolean state
Toggling means switching from true to false or false to true based on previous state.Step 2: Choose callback to avoid stale state
Usingprev => !prevensures the toggle uses the latest state safely.Final Answer:
setIsOpen(prev => !prev); -> Option DQuick Check:
Toggle boolean safely = callback with previous state [OK]
Hint: Toggle booleans with callback using previous state [OK]
Common Mistakes:
- Using direct negation causes stale state bugs
- Setting fixed true or false instead of toggling
- Not using callback for dependent state updates
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
