What is Redux?

Centralised Store

Redux keeps global application state in one store outside the component tree. Any component can read the part it needs and dispatch actions to change it — no props drilling.

Component ──dispatch(action)──► Reducer(state, action) ──► new State in Store
    ▲                                                          │
    └──────────────────── useSelector ◄────────────────────────┘

Three Principles

  1. Single source of truth: all global state in one store.
  2. State is read-only: the only way to change it is to dispatch an action ({ type: "cart/addItem", payload }).
  3. Changes are made with pure functions: reducers take (state, action) and return the next state.

The Same Flow with useReducer

Example

Redux works like the useReducer hook, but the store is shared by the whole app. This mini version uses Context + useReducer to show the flow.

import { createContext, useContext, useReducer } from 'react';

const StoreContext = createContext(null);

function cartReducer(state, action) {
  switch (action.type) {
    case 'cart/addItem': return { items: [...state.items, action.payload] };
    case 'cart/clear': return { items: [] };
    default: return state;
  }
}

function AddButtons() {
  const { dispatch } = useContext(StoreContext);
  return (
    <div>
      <button onClick={() => dispatch({ type: 'cart/addItem', payload: 'Pen' })}>Add Pen</button>
      <button onClick={() => dispatch({ type: 'cart/addItem', payload: 'Book' })}>Add Book</button>
      <button onClick={() => dispatch({ type: 'cart/clear' })}>Clear</button>
    </div>
  );
}

function CartBadge() {
  const { state } = useContext(StoreContext);
  return <p>🛒 {state.items.length} items: {state.items.join(', ')}</p>;
}

export default function App() {
  const [state, dispatch] = useReducer(cartReducer, { items: [] });
  return (
    <StoreContext.Provider value={{ state, dispatch }}>
      <CartBadge />
      <AddButtons />
    </StoreContext.Provider>
  );
}

Result