0
0
ReactConceptBeginner · 3 min read

What is Reducer in Redux: Simple Explanation and Example

In Redux, a reducer is a pure function that takes the current state and an action, then returns a new state. It decides how the state changes based on the action received, without modifying the original state.
⚙️

How It Works

Think of a reducer as a decision-maker for your app's data. It looks at the current state and an action (like a message saying what happened) and then decides what the new state should be. It never changes the old state directly but creates a new version with the updates.

This is similar to how a cashier at a store handles transactions: they see the current total and the new item being bought (the action), then calculate the new total without erasing the old one. This keeps your app's data predictable and easy to track.

💻

Example

This example shows a simple reducer that manages a counter. It increases or decreases the count based on the action type.

javascript
const initialState = { count: 0 };

function counterReducer(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

// Example usage:
const state1 = counterReducer(undefined, { type: 'INCREMENT' });
const state2 = counterReducer(state1, { type: 'INCREMENT' });
const state3 = counterReducer(state2, { type: 'DECREMENT' });

console.log(state3);
Output
{ count: 1 }
🎯

When to Use

Use a reducer in Redux when you need to manage complex state changes in a predictable way. It is especially helpful in apps where many parts of the UI depend on shared data that changes over time.

For example, in a shopping cart app, reducers handle adding or removing items, updating quantities, and calculating totals. This keeps your app organized and makes debugging easier because all state changes go through clear, simple functions.

Key Points

  • A reducer is a pure function that returns new state based on current state and action.
  • It never changes the original state directly, ensuring immutability.
  • Reducers help keep state management predictable and easy to debug.
  • They are central to how Redux manages app data flow.

Key Takeaways

A reducer takes current state and an action to return a new state without changing the original.
Reducers keep state changes predictable and easy to follow in Redux apps.
Use reducers to manage shared app data that changes over time, like counters or shopping carts.
Reducers must be pure functions with no side effects for reliable state updates.