Skip to content
LATEST

🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.

Upgradix
Upgradix Code. Learn. Ship.
Updated Nov 25, 2026

Scaling State with useReducer and Context API

Use useReducer to group complex, multi-step state updates into one predictable function. Pair it with Context API to share app-wide data like auth or theme across deep components without prop drilling, while keeping fast-changing state local.

Upgradix Admin
Upgradix Admin Verified Author

Super Admin

English 34 min read 30 WhatsApp

Scaling State with useReducer and Context API

Quick Answer: Use useReducer to group complex, multi-step state updates into one predictable function. Pair it with Context API to share app-wide data like auth or theme across deep components without prop drilling, while keeping fast-changing state local.

Imagine Lakshmi runs a grocery delivery app in Chennai. When a shopper logs in, switches to dark mode, or adds items with a coupon, five different screens must stay in sync.

At first, Lakshmi stores everything in separate useState hooks inside App.jsx and passes them down through four layers of components. Soon, updating one discount breaks the cart total, and every middle component is cluttered with props it never uses.

How do we manage complex state transitions cleanly and share global data without turning our React app into a mess?

1. Why Do We Need useReducer and Context API?

The problem without useReducer and Context

When an app grows, two separate state problems appear at the same time: scattered update logic and deep prop drilling.

Example 1: Tangled useState hooks and prop drilling in Lakshmi's grocery app

This works for a small demo, but quickly causes sync bugs as features grow.

function App() {
  const [user, setUser] = useState(null);
  const [theme, setTheme] = useState("light");
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  // Passing theme and user through Layout just to reach Navbar!
  return <Layout user={user} theme={theme} setTheme={setTheme} />;
}

This setup works on day one. However, it breaks down as soon as real features arrive.

  1. Related flags like isLoading, user, and error can fall out of sync if you forget one setter.
  2. Prop drilling forces middle components like Layout to accept and forward props they do not care about.
  3. Testing business rules is hard because update logic is scattered across ten button handlers.

The solution: useReducer + Context API

Reducer = a pure JavaScript function that takes the current state and an action, then returns the next state.

Context API = a built-in React channel that delivers data directly to any nested component without passing props manually.

By putting useReducer inside a Context Provider, Lakshmi centralizes all state rules in one place and teleports state directly to the components that need it.

Live Flow: Reducer State Cycle + Direct Context Delivery

Watch how Lakshmi's app processes an action in the reducer and updates deep components while skipping LayoutShell.

Action: IDLE { user: "Lakshmi", theme: "light", role: "admin" }

1. State Transition Engine (useReducer)

Lakshmi Clicks
dispatch({ type: "TOGGLE_THEME" })
appReducer()
Pure function computes next state
AppContext.Provider
Holds new immutable state

2. Context Delivery (Zero Prop Drilling)

Navbar
useContext() → updates theme
LayoutShell
Skipped! No props passed
CheckoutBar
useContext() → reads user
User Action Reducer / Consumer Context Provider Active Step

LayoutShell never receives or forwards state props. Both Navbar and CheckoutBar read directly from AppContext.

2. Consolidating Complex Transitions with useReducer

Action = a plain object with a type field that describes what just happened (like LOGIN_SUCCESS).

Instead of calling three separate setters when Lakshmi logs in, we dispatch one action. The reducer handles every related field atomically.

Example 2: Auth and theme reducer for the Chennai grocery app

All state transitions live in one pure, easy-to-test function.

export const initialState = {
  user: null,
  theme: "light",
  status: "idle",
  error: null
};

export function appReducer(state, action) {
  switch (action.type) {
    case "LOGIN_START":
      return { ...state, status: "loading", error: null };
    case "LOGIN_SUCCESS":
      return { ...state, status: "authenticated", user: action.payload };
    case "LOGIN_ERROR":
      return { ...state, status: "error", error: action.payload };
    case "TOGGLE_THEME":
      return { ...state, theme: state.theme === "light" ? "dark" : "light" };
    default:
      throw new Error(`Unknown action: ${action.type}`);
  }
}

Because appReducer is a pure function, it never mutates state directly. It always returns a fresh object, which makes debugging and unit testing straightforward.

3. Sharing State Cleanly with Split Contexts

A common performance trap is putting both state and dispatch into one single Context object. When you do that, even a button that only calls dispatch re-renders every time state changes.

Splitting them into two contexts (AppStateContext and AppDispatchContext) avoids unnecessary re-renders.

Example 3: Combining useReducer with split Context Providers

Components that only dispatch actions will not re-render when state updates.

import { createContext, useContext, useReducer } from "react";
import { appReducer, initialState } from "./appReducer";

const AppStateContext = createContext(null);
const AppDispatchContext = createContext(null);

export function AppProvider({ children }) {
  const [state, dispatch] = useReducer(appReducer, initialState);

  return (
    <AppStateContext.Provider value={state}>
      <AppDispatchContext.Provider value={dispatch}>
        {children}
      </AppDispatchContext.Provider>
    </AppStateContext.Provider>
  );
}

export const useAppState = () => useContext(AppStateContext);
export const useAppDispatch = () => useContext(AppDispatchContext);

Now any deep component like Navbar can toggle the theme in two clean lines:

function ThemeToggleButton() {
  const dispatch = useAppDispatch();
  return <button onClick={() => dispatch({ type: "TOGGLE_THEME" })}>Switch Theme</button>;
}

Because React guarantees that dispatch keeps the same reference across renders, ThemeToggleButton stays fast and never re-renders unnecessarily.

4. When NOT to Overuse Context

Performance Warning: Context is a dependency injection tool, not a high-frequency state manager. Every component reading a Context re-renders whenever that Context value changes.

Follow these three rules to keep your app fast:

  • Good for Context: Low-frequency global data like current logged-in user, UI theme, language locale, or feature flags.
  • Bad for Context: Fast-changing data like search input keystrokes, mouse coordinates, or a 1,000-row live stock ticker.
  • Split by domain: Keep AuthContext and ThemeContext separate so changing the theme does not re-render auth-only components.

5. useState + Props vs. useReducer + Context API

Choosing the right React state pattern
useState + Props useReducer + Context API
Best for simple, isolated UI state (modals, form inputs). Best for multi-step transitions and shared cross-cutting state.
Explicit data flow, easy to trace 1–2 levels deep. Eliminates prop drilling across 4+ nested layers.
Logic spreads across event handlers as state grows. Centralizes all rules in one pure, testable reducer.

The important terms to remember

  • Reducer = a pure function (state, action) => newState that centralizes state transitions.
  • Dispatch = the stable function used to send an action object to the reducer.
  • Prop Drilling = passing props through intermediate components that do not use them.
  • Cross-Cutting State = app-wide data needed by many unrelated screens, such as auth or theme.

6. Common Mistakes to Avoid

1. Mutating state directly inside the reducer

Writing state.theme = "dark"; return state; breaks React's change detection. React sees the same object reference and skips the re-render.

Better approach: Always return a new object using the spread operator: return { ...state, theme: "dark" };.

2. Putting the entire app's state into one giant Context

Combining cart items, search filters, theme, and auth into one mega-context forces the whole component tree to re-render on every single keystroke.

Better approach: Keep local state local with useState, split contexts by domain, and use a dedicated store like Redux Toolkit or Zustand for high-frequency global state.

3. Creating a new object inline in the Provider value

Writing value={{ state, dispatch }} directly in JSX creates a brand-new object on every parent render, forcing all consumers to re-render.

Better approach: Split state and dispatch into separate contexts, or wrap the combined object in useMemo.

7. Interview Questions & Practice

Question 1: Why does Context API cause performance issues when overused?

What the interviewer expects: Understanding of React's re-render propagation when a Context value changes.

Strong answer: "When a Context Provider's value changes, every component calling useContext on it re-renders, even if it only uses one small field of that object. In Lakshmi's grocery app, if we put search text and auth in the same Context, typing one letter would re-render the Navbar and CheckoutBar. To prevent this, we split contexts by domain and keep fast-changing state local."

Question 2: When would you choose useReducer over useState?

What the interviewer expects: Recognizing complex state transitions and next-state dependencies.

Strong answer: "I use useState for independent values like a toggle or text input. I switch to useReducer when multiple fields must change together, like setting status: 'authenticated', saving user, and clearing error in one atomic step."

What interviewers expect at different levels

  • Junior developer: Knows how to create a Context, wrap a Provider, and read it with useContext.
  • Senior developer: Explains how to split state/dispatch contexts, avoid inline object values, and test reducers in isolation.
  • Technical architect: Knows the boundary between Context API, server-state tools (React Query), and external stores (Redux Toolkit / Zustand).

Beginner: Hospital appointment theme switcher

Build a ThemeContext with useReducer that supports TOGGLE_THEME and SET_FONT_SIZE for a hospital portal.

Expected result: Clicking a button in the footer updates the theme and font size in the header without passing props through the main layout.

Intermediate: UPI checkout cart reducer

Write a cartReducer supporting ADD_ITEM, REMOVE_ITEM, and APPLY_COUPON where the total price recalculates automatically on every action.

Hint: Never mutate the items array; use map, filter, or spread syntax to return a new array.

Advanced: Prevent wasted re-renders in a dashboard

Take an app with one combined AppContext holding user, theme, and notifications, and refactor it so adding a notification does not re-render the ThemeToggle button.

  • Split NotificationContext out of AppContext.
  • Separate StateContext and DispatchContext.
  • Verify with React DevTools Profiler that ThemeToggle stays idle.

Challenge: Add a custom hook that throws a clear error if used outside its Provider.

8. Next Steps

  • Refactor one prop-drilled feature in your current React project (such as Auth or Theme) to use useReducer with split Contexts.
  • Explore dedicated state libraries like Redux Toolkit or Zustand when your app needs high-frequency global updates or built-in dev tools.
Upgradix Admin
Written by Upgradix Admin

Upgradix Admin is the Founder of Shrash Studio and creator of Upgradix by Shrash Studio. With 15+ years of experience in software development and architecture across .NET, C#, Web API .NET Core, React.js, Angular, microservices, AWS, MS SQL Server, MongoDB, and AI/ML, he shares practical tutorials and hands-on insights while building an open platform where anyone can contribute knowledge and earn goodies.

Share what you know: Anyone can join Upgradix, publish helpful guides, and earn goodies for sharing knowledge.

Write & Earn Goodies

Discussion & Comments

0
Guest mode · Login / Register
Post directly as a guest or log in first.

No comments yet

Start the discussion above — ask a question, share a tip, or reply to a comment.

This article is protected. Printing and saving as PDF are disabled.