BeginnerCoder

Lesson 23 — Store with reducer + context

A tiny store of your own

A store is one place that holds app-wide state and the actions that change it. Build it from three parts: a Provider component that owns useReducer and shares it through context, a reducer with the rules, and a custom hook (useStore) so components never touch the context directly. The hook can also throw a clear error when it is used outside the Provider.

function useStore() {
  const ctx = useContext(StoreContext);
  if (!ctx) throw new Error("useStore must be used inside StoreProvider");
  return ctx;
}

Why it matters: this is Redux-style state management with no library, and it is how many real apps start.

Want it another way?
Task

Make useStore return the real store from context. Clicking Add Tea and Add Cake should show "Cart: 2 items".

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