MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Combining useReducer with Context API0%
Study Materials
React.js for IntermediateProgress 0%
1.1Component Reusability and Polymorphic Components1.2Render Props Pattern in Modern React1.3Higher-Order Components vs Modern Hooks1.4Compound Components Pattern Explained
6.1When to Choose useReducer Over useState6.2Reducer Functions, Actions, and Dispatch6.3Managing Complex State Transitions with useReducer6.4Combining useReducer with Context API
HomeTutorialsReact.js for IntermediateCombining useReducer with Context API
Fetching REST APIs with Async Await and State

Combining useReducer with Context API

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

1. The Ultimate Lightweight Global State Pattern

For small applications, useState is sufficient. For massive enterprise applications with dozens of developers, Redux Toolkit or Zustand are common choices.

However, for mid-sized applications, design systems, and modular feature trees, combining useReducer with the Context API provides a complete, scalable state management architecture with zero external dependencies!

1 [Root Context Provider]
2 (Holds useReducer state & dispatch)
3 │
4 ┌───────────────┴───────────────┐
5 ▼ ▼
6[useCart() - Reads State] [useCartDispatch() - Sends Actions]
7(Catalog, Cart Drawer, Badges) (Add Button, Remove Button, Checkout)

2. Implementing the Combined Cart Store

Let's build a production-grade shopping cart store:

1// src/context/CartContext.jsx
2import React, { createContext, useContext, useReducer, useEffect } from 'react';
3 
4// 1. Define Separate State and Dispatch Contexts
5const CartStateContext = createContext(null);
6const CartDispatchContext = createContext(null);
7 
8const STORAGE_KEY = 'msk_cart_state';
9 
10// 2. Reducer Function
11function cartReducer(state, action) {
12 switch (action.type) {
13 case 'ADD_TO_CART': {
14 const exists = state.find(item => item.id === action.payload.id);
15 if (exists) {
16 return state.map(item =>
17 item.id === action.payload.id
18 ? { ...item, quantity: item.quantity + 1 }
19 : item
20 );
21 }
22 return [...state, { ...action.payload, quantity: 1 }];
23 }
24 
25 case 'REMOVE_FROM_CART':
26 return state.filter(item => item.id !== action.payload);
27 
28 case 'CLEAR_CART':
29 return [];
30 
31 default:
32 throw new Error(`Unhandled action type: ${action.type}`);
33 }
34}
35 
36// 3. Provider Component
37export function CartProvider({ children }) {
38 // Initialize state lazily from localStorage
39 const [cart, dispatch] = useReducer(cartReducer, [], () => {
40 try {
41 const saved = localStorage.getItem(STORAGE_KEY);
42 return saved ? JSON.parse(saved) : [];
43 } catch {
44 return [];
45 }
46 });
47 
48 // Sync to localStorage
49 useEffect(() => {
50 localStorage.setItem(STORAGE_KEY, JSON.stringify(cart));
51 }, [cart]);
52 
53 return (
54 <CartStateContext.Provider value={cart}>
55 <CartDispatchContext.Provider value={dispatch}>
56 {children}
57 </CartDispatchContext.Provider>
58 </CartStateContext.Provider>
59 );
60}
61 
62// 4. Custom Consumer Hooks
63export function useCart() {
64 const context = useContext(CartStateContext);
65 if (!context) {
66 throw new Error('useCart must be used within a <CartProvider>');
67 }
68 return context;
69}
70 
71export function useCartDispatch() {
72 const context = useContext(CartDispatchContext);
73 if (!context) {
74 throw new Error('useCartDispatch must be used within a <CartProvider>');
75 }
76 return context;
77}

3. High-Performance Consumer Usage

Component 1: Navbar Badge (Reads State Only)

1import React from 'react';
2import { useCart } from '../context/CartContext';
3 
4export default function CartBadge() {
5 const cart = useCart(); // Subscribed to state updates
6 const totalQuantity = cart.reduce((sum, item) => sum + item.quantity, 0);
7 
8 return <div className="badge">Cart: {totalQuantity}</div>;
9}

Component 2: Add Button (Dispatches Actions Only)

1import React from 'react';
2import { useCartDispatch } from '../context/CartContext';
3 
4export default function AddToCartButton({ course }) {
5 const dispatch = useCartDispatch(); // Consumes STABLE dispatch reference!
6 
7 return (
8 <button
9 onClick={() => dispatch({ type: 'ADD_TO_CART', payload: course })}
10 className="btn-add"
11 >
12 Enroll Now (${course.price})
13 </button>
14 );
15}

Because AddToCartButton only consumes CartDispatchContext, it will NEVER re-render when items are added to the cart!


Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What makes combining useReducer with Context an attractive state management solution?
Question 2
Why are two separate contexts (CartStateContext and CartDispatchContext) created?
Question 3
How is initial state lazily loaded in useReducer(cartReducer, [], initializerFunction)?
Question 4
What happens if an unknown action type is dispatched to a reducer that ends with throw new Error(...)?
Question 5
How do consumer components add items to the cart when using this architecture?
Next Lesson

Fetching REST APIs with Async Await and State

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Managing Complex State Transitions with useReducerFetching REST APIs with Async Await and State

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext