BeginnerCoder

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.

Want it another way?
Task

Handle the "dec" action. The console should print 6 4, and clicking − twice should show -2.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with React Foundations

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.