useReducer Dispatch
Predict Output Medium
Question
What does this code print?
Code
function reducer(s, a) {
if (a.type === "add") return s + 1;
return s;
}
function App() {
const [s, d] = useReducer(reducer, 0);
d({type:"add"}); d({type:"add"});
return <p>{s}</p>;
}
// After processing
Hint
Each dispatch processes the reducer in order.
Explanation
useReducer starts at 0. First dispatch {type:"add"} returns 0+1=1. Second dispatch returns 1+1=2. The state becomes 2.
Related Resources
Related Lessons
- useReducer
Learn useReducer.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.