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
Reducer Functions, Actions, and Dispatch0%
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 IntermediateReducer Functions, Actions, and Dispatch
Managing Complex State Transitions with useReducer

Reducer Functions, Actions, and Dispatch

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

1. The Anatomy of Reducer Architecture

The reducer pattern rests on three interconnected pillars:

  1. 1
    The State: The current data snapshot of your component or feature.
  2. 2
    The Action: A plain JavaScript object describing an event that occurred.
  3. 3
    The Dispatch Function: The communication channel used to send actions to the reducer.
  4. 4
    The Reducer: The pure decision-maker function that calculates the next state.
1[User clicks "Enroll"]
2 │
3 ▼
4dispatch({ type: 'ENROLL_STUDENT', payload: { id: 42, name: 'Ananya' } })
5 │
6 ▼
7[Pure Reducer Function: (state, action) => newState]
8 │
9 ▼
10[React updates state and triggers re-render]

2. Anatomy of an Action Object

By convention across the JavaScript and React ecosystem (Flux Standard Action pattern), an action object contains:

  • type (Required): A descriptive string in UPPER_SNAKE_CASE or domain/event format stating what happened.
  • payload (Optional): Any data required to execute the transition (e.g. an ID, an input string, an object).
1// Examples of descriptive, semantic actions:
2{ type: 'TODO_ADDED', payload: 'Master React Reducers' }
3{ type: 'FILTER_CHANGED', payload: 'completed' }
4{ type: 'ITEM_DELETED', payload: 104 }
5{ type: 'FORM_RESET' }

3. Writing Pure Reducer Functions

A reducer must adhere strictly to the rules of pure functions:

  • Zero Side Effects: Never initiate API calls, start timers, modify localStorage, or trigger random numbers inside a reducer.
  • Strict Immutability: Never mutate state in place. Always use object spread (...state) and non-mutating array methods (map, filter).
  • Deterministic: Given the same state and action, it must always return the exact same output.
1export const initialCartState = {
2 items: [],
3 discountCode: null,
4 totalPrice: 0
5};
6 
7export function cartReducer(state, action) {
8 switch (action.type) {
9 case 'ADD_ITEM': {
10 const existingIndex = state.items.findIndex(i => i.id === action.payload.id);
11 let updatedItems;
12 
13 if (existingIndex > -1) {
14 // Increment quantity immutably
15 updatedItems = state.items.map((item, idx) =>
16 idx === existingIndex ? { ...item, quantity: item.quantity + 1 } : item
17 );
18 } else {
19 // Add new item immutably
20 updatedItems = [...state.items, { ...action.payload, quantity: 1 }];
21 }
22 
23 return {
24 ...state,
25 items: updatedItems,
26 totalPrice: updatedItems.reduce((acc, i) => acc + i.price * i.quantity, 0)
27 };
28 }
29 
30 case 'REMOVE_ITEM': {
31 const filtered = state.items.filter(i => i.id !== action.payload);
32 return {
33 ...state,
34 items: filtered,
35 totalPrice: filtered.reduce((acc, i) => acc + i.price * i.quantity, 0)
36 };
37 }
38 
39 case 'APPLY_DISCOUNT': {
40 return {
41 ...state,
42 discountCode: action.payload,
43 totalPrice: state.totalPrice * 0.9 // 10% off
44 };
45 }
46 
47 case 'CLEAR_CART':
48 return initialCartState;
49 
50 default:
51 // Return unchanged state or throw error for unrecognized actions
52 return state;
53 }
54}

4. The Stability of dispatch

In React, the dispatch function returned by useReducer is guaranteed to have a stable identity across all renders.

React guarantees that dispatch will never change its reference between re-renders. This means:

  • You do not need to include dispatch in useEffect or useCallback dependency arrays.
  • Passing dispatch down through props or Context will never trigger unnecessary child re-renders!

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What two properties are standard on a Flux Standard Action object?
Question 2
What should happen if a reducer receives an unknown action type that it does not handle?
Question 3
Why is performing an asynchronous fetch() inside a reducer function strictly forbidden?
Question 4
Does the dispatch function returned by useReducer change reference between component re-renders?
Question 5
What makes reducers exceptionally easy to unit test compared to components?
Next Lesson

Managing Complex State Transitions with useReducer

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

Related Lessons

Previous LessonNext Lesson
When to Choose useReducer Over useStateManaging Complex State Transitions with useReducer

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