You pass a function to setState() to get the actual state at the time of change 🔄 This is important because setState works asynchronously!
// ❌ Can break:
setState({count: state.count + 1});
// ✅ Correct:
setState(prevState => ({count: prevState.count + 1}));
setState(prev => ({count: prev.count + 1})); // 0 + 1 = 1
Passing a function to setState() — like asking a friend to remember exactly what to buy, instead of writing the list again! 🛒
React updates state asynchronously — not immediately:
// ❌ Problem:
function handleClick() {
// Let's say count = 0
setState({count: state.count + 1}); // 0 + 1 = 1
setState({count: state.count + 1}); // 0 + 1 = 1 (again!)
setState({count: state.count + 1}); // 0 + 1 = 1 (and again!)
// Result: count = 1, not 3!
}Why this happens:
Function gets the actual previous state:
// ✅ Solution:
function handleClick() {
setState(prev => ({count: prev.count + 1})); // 0 + 1 = 1
setState(prev => ({count: prev.count + 1})); // 1 + 1 = 2
setState(prev => ({count: prev.count + 1})); // 2 + 1 = 3
// Result: count = 3 ✅
}How it works:
// ✅ Needed for multiple consecutive changes
const increment = () => {
setState(prev => ({count: prev.count + 1}));
setState(prev => ({count: prev.count + 1}));
setState(prev => ({count: prev.count + 1}));
};// ✅ When new state depends on old
const toggle = () => {
setState(prev => ({isOpen: !prev.isOpen}));
};
const addItem = () => {
setState(prev => ({
items: [...prev.items, newItem]
}));
};// ✅ Can do without function if completely replacing
setState({name: 'New name'});
setState({age: 25});
setState({isLoggedIn: true});// ✅ Doesn't depend on previous state
const resetForm = () => {
setState({
name: '',
email: '',
message: ''
});
};// ❌ Mistake — thinking setState is synchronous
const handleClick = () => {
setState({count: state.count + 1});
console.log(state.count); // Old value!
};
// ✅ Correct — use useEffect or callback// ❌ Mistake — mixing in one handler
const handleClick = () => {
setState({count: state.count + 1}); // ❌
setState(prev => ({count: prev.count + 1})); // ✅
setState({count: state.count + 1}); // ❌
};Passing a function to setState() — like getting fresh information before making decisions! 💡
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪