The Redux Flow: Predictable State

The Redux Flow: Predictable State in JavaScript: Imagine a giant bank vault. You can't just walk in and take money.

Concept Explanation

Imagine a giant bank vault. You can't just walk in and take money. You have to submit a Withdrawal Slip (an Action) to the Teller (the Reducer). The Teller checks the rules, updates the Main Ledger (the Store), and then tells you the new balance.

This is Redux. It makes state changes predictable because you can't touch the data directly—you can only "Dispatch" an action that describes what you want to change.


The Three Pillars

  1. Store: The single source of truth (one big JS object).
  2. Actions: Plain objects that describe what happened ({ type: 'DEPOSIT', amount: 10 }).
  3. Reducers: Functions that take the Old State + Action and return a New State.

Syntax or Core Structure

// 1. The Reducer (The Logic)
const counterReducer = (state = { count: 0 }, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return { count: state.count + 1 };
        default:
            return state;
    }
};

// 2. The Store (The Data)
// In a real app: import { createStore } from 'redux';
// const store = createStore(counterReducer);

// 3. The Dispatch (The Trigger)
// store.dispatch({ type: 'INCREMENT' });

Best Practices

  • Immutability: Never do state.count++. Always return a NEW object: return { ...state, count: state.count + 1 }.
  • Pure Functions: Reducers must be pure. Never call an API or generate a random number inside a reducer.
  • Action Types as Constants: Use const INCREMENT = "INCREMENT" to avoid typos.

Practice Exercises

  1. The Shopping Cart: Write a reducer that handles two actions: ADD_ITEM and REMOVE_ITEM.
  2. The Immutability Test: Write a function that "updates" an object's nested property without mutating the original object.
  3. The Logger: Research "Redux Middleware" and explain how it allows you to log every action before it hits the store.