Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 132 ยท Context and Shared State

Classic Redux with react-redux

Understand classic Redux and react-redux - createStore, reducers, combineReducers, middleware, redux-thunk, connect, mapStateToProps and selectors - and why Redux Toolkit replaced the boilerplate.

Redux is the most famous state library in the React world, and a huge amount of production code was written in what we now call classic Redux: hand-written action types, switch-statement reducers, createStore, connect and mapStateToProps. Today new projects use Redux Toolkit, which removes most of that ceremony (see Redux Toolkit and Zustand), but Redux Toolkit is built on exactly the ideas below. If you can read classic Redux, you can maintain old code, understand Toolkit's output, and answer the interview questions that still ask for it.

The redux and react-redux packages cannot be installed in the editor, so the real code is shown read-only and each concept has a runnable stand-in written by hand in a few dozen lines. The stand-ins are for learning; use the real libraries in your projects.

The three ideas

Redux makes state changes predictable with three rules.

  1. One store holds the whole application state as a single object tree.
  2. State is read-only. The only way to change it is to dispatch an action, a plain object describing what happened: { type: 'cart/added', payload: { id: 7 } }.
  3. A reducer is a pure function (state, action) => newState that computes the next state. It never mutates the old state, never calls an API, never reads the clock or random numbers. Same inputs, same output.

The data flows in one direction: the UI dispatches an action, the store runs the reducer, the new state is saved, and subscribers (your components) are told to update. This is the same loop as useReducer, which you met in Reducers, moved outside React and made global.

flowchart LR
  UI["Component"] -->|"dispatch(action)"| S["Store"]
  S -->|"(state, action)"| R["Reducer"]
  R -->|"new state"| S
  S -->|"notifies subscribers"| UI

One-way data flow in Redux.

Actions, action creators and reducers

An action creator is a function that returns an action object. It keeps the shape in one place and avoids typos in the type string.

JavaScript
// actions.js (read-only)
export const ADD_TODO = 'todos/added';
export const TOGGLE_TODO = 'todos/toggled';

export const addTodo = (text) => ({ type: ADD_TODO, payload: { id: Date.now(), text } });
export const toggleTodo = (id) => ({ type: TOGGLE_TODO, payload: { id } });
JavaScript
// todosReducer.js (read-only)
const initialState = [];

export function todosReducer(state = initialState, action) {
  switch (action.type) {
    case ADD_TODO:
      return [...state, { ...action.payload, done: false }];
    case TOGGLE_TODO:
      return state.map((todo) =>
        todo.id === action.payload.id ? { ...todo, done: !todo.done } : todo
      );
    default:
      return state; // unknown action: return the same state
  }
}

Two habits you will see everywhere: the default branch returns the same state object (so subscribers can tell nothing changed), and every case returns a new array or object rather than editing the old one. Objects and arrays in state explains why.

createStore and combineReducers

createStore(reducer) from the redux package builds the store. It exposes three methods you need to know: getState(), dispatch(action) and subscribe(listener). Real apps have many slices of state, so combineReducers merges several reducers into one, each managing one key of the state object.

JavaScript
// store.js (read-only; classic Redux)
import { createStore, combineReducers } from 'redux';

const rootReducer = combineReducers({
  todos: todosReducer,
  filter: filterReducer,
});

export const store = createStore(rootReducer);

store.subscribe(() => console.log(store.getState()));
store.dispatch(addTodo('Learn Redux'));

(Since Redux 5 createStore is marked deprecated in the type definitions, in favor of configureStore from Redux Toolkit. It still works.)

The runnable version below implements the three methods, combineReducers, and logs every action with the state before and after. Run it and read the output: this is the entire Redux core.

A tiny Redux core: createStore and combineReducers

The console shows the full state after each dispatch. Notice that App had to be told to render again by hand (rerender), because nothing connects the store to React yet. That connection is what react-redux is for.

Middleware and redux-thunk

A reducer must be pure, so where do API calls go? Into middleware: a function that sits between dispatch and the reducer and can inspect, delay, log or transform actions. The classic example is redux-thunk: if you dispatch a function instead of an object, the middleware calls it with dispatch and getState, so it can do async work and dispatch ordinary actions when done.

JavaScript
// read-only
import { createStore, applyMiddleware } from 'redux';
import { thunk } from 'redux-thunk';

const store = createStore(rootReducer, applyMiddleware(thunk));

// A thunk action creator:
export const loadUser = (id) => async (dispatch) => {
  dispatch({ type: 'user/loading' });
  try {
    const response = await fetch(`/api/users/${id}`);
    dispatch({ type: 'user/loaded', payload: await response.json() });
  } catch (error) {
    dispatch({ type: 'user/failed', error: error.message });
  }
};

store.dispatch(loadUser(7)); // dispatching a function

The three actions (loading, loaded, failed) are the Redux version of the status flag you learned in data fetching. Other middleware you will meet: redux-logger (prints each action), redux-saga (async flows as generator functions) and redux-observable (RxJS). Redux Toolkit's createAsyncThunk is a packaged version of the pattern above.

Middleware is a chain of three nested functions, store => next => action => ..., and each one decides whether to call next(action) to pass the action on. A runnable version with a logger and a thunk:

Middleware: logger and thunk

react-redux: Provider, connect and the hooks

react-redux links a store to components. You wrap the app in <Provider store={store}>, which puts the store in context (see Context). Components then subscribe in one of two ways.

The classic way: connect. It is a higher-order component: connect(mapStateToProps, mapDispatchToProps)(Component) returns a new component that reads state, passes the results and bound action creators in as props, and re-renders only when those props change.

JSX
// TodoList.jsx (read-only; classic react-redux)
import { connect } from 'react-redux';
import { toggleTodo } from './actions';

function TodoList({ todos, onToggle }) {
  return (
    <ul>
      {todos.map((t) => (
        <li key={t.id} onClick={() => onToggle(t.id)}>{t.text}</li>
      ))}
    </ul>
  );
}

const mapStateToProps = (state) => ({
  todos: state.todos.filter((t) => state.filter === 'all' || t.done === (state.filter === 'done')),
});

const mapDispatchToProps = { onToggle: toggleTodo }; // object shorthand: auto-dispatches

export default connect(mapStateToProps, mapDispatchToProps)(TodoList);

The modern way: hooks. Since 2019, useSelector(selector) reads state and subscribes, and useDispatch() returns dispatch. They give the same result with far less wrapper code, and they are what Redux Toolkit documentation uses.

JSX
// read-only
import { useSelector, useDispatch } from 'react-redux';

function TodoList() {
  const todos = useSelector(selectVisibleTodos);
  const dispatch = useDispatch();
  return <ul>{todos.map((t) => <li key={t.id} onClick={() => dispatch(toggleTodo(t.id))}>{t.text}</li>)}</ul>;
}

What mapStateToProps really does

mapStateToProps runs whenever the store changes, and connect compares the returned props shallowly with the previous ones. If you return todos: state.todos.filter(...), the filter creates a new array every time, so the shallow comparison always fails and the component re-renders on every store update. The same trap exists for useSelector with inline .filter() or object literals. The cure is selectors with memoization (createSelector from the reselect library) that return the same array while the inputs are unchanged. Here is the connection with the stand-in store, including that trap:

A tiny Provider, useSelector and connect

useSyncExternalStore is what the real react-redux v8 and later use inside useSelector, which is why the stand-in is short. Look at what the stand-in needs to work: connect compares mapState's result shallowly (shallowEqual), because (s) => ({ items: s.items }) builds a new object on every call, and useSyncExternalStore would loop forever on an ever-changing snapshot. The real library does the same comparison for you; see external stores for why snapshots must be stable.

Why Redux Toolkit replaced all this

Classic Redux works, but it asked you to write a lot of code that never changed from project to project:

Classic Redux chore Redux Toolkit
Action type constants and action creators for each action createSlice generates both from the reducer functions
Switch statements with careful spreading Reducers may "mutate" a draft (Immer turns that into an immutable update)
createStore + applyMiddleware + DevTools wiring configureStore sets up thunk, DevTools and checks for mistakes
Hand-written loading, success and failure actions createAsyncThunk (and RTK Query for data fetching)
Memoized selectors via reselect createSelector is re-exported

The core ideas (one store, plain actions, pure reducers, middleware) did not change. The official guidance is: use Redux Toolkit for all new Redux code, and consider whether you need a global store at all: for server data a tool such as TanStack Query is usually a better fit, and for small apps Context or Zustand are enough. State management helps you choose.

Common mistakes

  • Mutating state in a reducer (state.push(x)). The store then holds the same object, subscribers see no change and the UI does not update.
  • Side effects in reducers, such as fetch, Date.now() or Math.random(). Put them in the action creator or middleware.
  • Putting everything in Redux. Form fields, hover state and open/closed flags usually belong in local component state.
  • Selectors that return a new object or array every call. They make components re-render on every dispatch; memoize them.
  • Duplicated state, such as storing both a list and its length. Derive values in selectors.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What are the three principles of Redux?

    Redux keeps one source of truth, changes it only through actions, and computes new state with pure functions.
  2. 2. What does a reducer return for an action type it does not know?

    Returning the same state object tells subscribers nothing changed. Returning undefined would erase the state.
  3. 3. What does redux-thunk allow you to dispatch?

    The middleware intercepts function actions and calls them, which is the classic place for API calls and for dispatching loading, success and error actions.
  4. 4. Why can mapStateToProps = (state) => ({ items: state.items.filter(...) }) cause needless re-renders?

    A new array is never === the old one. Use a memoized selector (reselect's createSelector) to return the same array while the inputs are unchanged.
  5. 5. What does Redux Toolkit's createSlice remove from classic Redux?

    A slice generates action creators and types from reducer functions, and Immer lets those reducers use mutating syntax safely.

Summary

  • Redux has one store, changes state only through dispatched actions and computes it with pure reducers.
  • createStore gives getState, dispatch and subscribe; combineReducers merges slice reducers.
  • Middleware wraps dispatch; redux-thunk lets you dispatch functions for async work.
  • react-redux provides Provider, connect(mapStateToProps, mapDispatchToProps) and the hooks useSelector and useDispatch.
  • Return stable values from selectors (memoize with createSelector) to avoid pointless renders.
  • Redux Toolkit is the modern way to write Redux; see the next lessons for it and for lighter alternatives.

Next: Redux Toolkit and Zustand Walkthrough