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
- Single source of truth — one
storeholds the entire app state tree. - State is read-only — the only way to change state is to dispatch an
action(a plain object with atypefield). - Changes via pure functions — reducers 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 key | Reducer file | Manages |
|---|---|---|
burger | store/reducer/burgerBuilder.js | Ingredients, totalPrice, error, building flag |
order | store/reducer/order.js | Order list, loading, purchased flag |
auth | store/reducer/auth.js | Token, 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
- react — UI library Redux is commonly paired with
- single-page-application — the architectural pattern that benefits from centralised state
- schwarzmuller-2021-react-burger-app — source repo