BeginnerCoder

Lesson 22 — Reducer + context (expert)

Reducer + context = app state

Put the [state, dispatch] from useReducer into a context, and any component can read the state or dispatch actions without props. Actions are usually objects with a type field, like { type: "reset" }, so they can carry extra data later.

const { dispatch } = useContext(CartContext);
dispatch({ type: "add", item: "tea" });

Why it matters: this is the same idea Redux and many state libraries are built on.

Want it another way?
Task

Make ResetButton dispatch { type: "reset" }. Clicking +1 three times shows "Count 3"; Reset brings it back to "Count 0".

← 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.