Redux

Redux is a predictable state management library for JavaScript applications. It stores all application state in a single store, enforces that state can only be changed by dispatching actions through reducer functions, and makes every state transition traceable. It is commonly paired with react via the react-redux bindings.


Core Principles

  1. Single source of truth — one store holds the entire app state tree.
  2. State is read-only — the only way to change state is to dispatch an action (a plain object with a type field).
  3. Changes via pure functionsreducers are pure functions (state, action) => newState; they must never mutate state or produce side effects.

Architecture in burgerApp

Three reducer slices combined with combineReducers:

Slice keyReducer fileManages
burgerstore/reducer/burgerBuilder.jsIngredients, totalPrice, error, building flag
orderstore/reducer/order.jsOrder list, loading, purchased flag
authstore/reducer/auth.jsToken, userId, auth errors, redirect path

Immutable Updates

Reducers return new state objects using the spread operator:

case actionTypes.ADD_INGREDIENT:
  return {
    ...state,
    ingredients: {
      ...state.ingredients,
      [action.ingredientName]: state.ingredients[action.ingredientName] + 1,
    },
    totalPrice: state.totalPrice + INGRDIENTS_PRICE[action.ingredientName],
  };

Async with redux-thunk

Plain Redux only supports synchronous action creators. redux-thunk middleware allows action creators to return a function (instead of an action object), enabling async operations:

export const auth = (email, password, isSignup) => {
  return (dispatch) => {
    dispatch(authStart());
    axios.post(url, data)
      .then(res => dispatch(authSuccess(res.data.idToken, res.data.localId)))
      .catch(err => dispatch(authFail(err.response.data.error)));
  };
};

Connecting to React

react-redux provides:

  • <Provider store={store}> — makes the store available to all descendant components via context.
  • connect(mapStateToProps, mapDispatchToProps) — injects selected state slices and bound action dispatchers as props into a component.

See Also