Lesson 16 — useReducer
State changes through actions
useReducer(reducer, initial) is an alternative to useState for state with several kinds of change. A reducer is a pure function (state, action) => newState: it gets the current state and an action describing what happened, and returns the next state. Components call dispatch(action). Because the reducer is a plain function, you can test it with console.log, without any UI.
function reducer(state, action) {
if (action === "reset") return 0;
return state;
}
console.log(reducer(7, "reset")); // 0
Why it matters: all the update rules live in one place, which makes complex state easy to follow and test.
Handle the "dec" action. The console should print 6 4, and clicking − twice should show -2.
A quick 3-question quiz on this lesson — instant feedback.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based React Foundations courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for React Foundations books — check the publication year so the examples match current versions.
Search Amazon →