Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 41 ยท Redux with React

Connect and Legacy Redux

Read and migrate older Redux code: connect with mapStateToProps and mapDispatchToProps, class components, hand-written reducers and action constants, and how each maps to hooks and Redux Toolkit.

Before hooks existed, React-Redux had one way to attach a component to the store: the connect higher-order function. Millions of lines of that code are still in production. You will meet it in job interviews, in older libraries and in any codebase older than 2019, and class components can only use connect, because hooks do not work in classes.

connect is still supported in React-Redux 9, but the official recommendation is hooks for new code. This lesson teaches you to read connect, to write it when you must, and to migrate legacy patterns step by step.

connect comes from react-redux, which our editor cannot load. The examples start with a block marked STAND-IN that implements a connect with the same call shape (mapState, mapDispatch as a function or object, ownProps) on top of a useSelector-style hook.

How connect works

connect(mapStateToProps, mapDispatchToProps) returns a function that takes your component and returns a new, connected component. The connected component reads the store, calls your two mapping functions and passes the results to your component as props.

JSX
// needs react-redux (read-only here)
import { connect } from 'react-redux';
import { added, removed } from './todosSlice';

function TodoCount({ count, onAdd }) {
  return <button onClick={() => onAdd('New todo')}>Todos: {count}</button>;
}

const mapStateToProps = (state, ownProps) => ({
  count: state.todos.items.length,
});

const mapDispatchToProps = (dispatch) => ({
  onAdd: (text) => dispatch(added(text)),
});

export default connect(mapStateToProps, mapDispatchToProps)(TodoCount);
  • mapStateToProps(state, ownProps) picks values from the state. It runs after every dispatch; the component re-renders only when the result changes by shallow equality (each prop compared with ===). Like selectors, it should not build new objects or arrays inside the returned props.
  • mapDispatchToProps provides function props. It can be a function (dispatch, ownProps) => ({...}) or, more simply, an object of action creators, which connect wraps in dispatch for you:
JSX
export default connect(mapStateToProps, { onAdd: added, onRemove: removed })(TodoCount);
  • If you pass no mapDispatchToProps, your component receives a dispatch prop. If you pass no mapStateToProps, the component never re-renders because of store updates.

Connect with a class component

Because classes cannot call hooks, connect is how class components talk to Redux:

A class component connected to the store

Counter has no idea Redux exists: it receives value, onIncrement and onReset as props and can be tested or reused without a store. That separation of "presentational" component and "container" logic was the main selling point of connect.

The same component with hooks

With hooks, the container and the component are the same function:

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

function Counter({ label }) {
  const value = useSelector((state) => state.value);
  const dispatch = useDispatch();
  return (
    <div>
      <h3>{label}: {value}</h3>
      <button onClick={() => dispatch(incremented())}>+1</button>
      <button onClick={() => dispatch(reset())}>reset</button>
    </div>
  );
}

Less code, no wrapper component in DevTools, simpler TypeScript. Both produce the same result; let the next example prove it, and see how each connect piece maps to a hook:

connect and hooks side by side

Toggle the second todo: only rows 2 re-render (look at the counters), whether they use connect or hooks. The optimisation work is the same; connect just hides it in a wrapper.

Translating connect to hooks

connect Hooks
mapStateToProps useSelector(selector) calls
mapDispatchToProps object or function const dispatch = useDispatch() and call dispatch(action())
ownProps argument Close over props in the selector: useSelector((s) => select(s, props.id))
Shallow comparison of the props object Select separately, or useSelector(sel, shallowEqual)
connect(...)(Component) wrapper The hook calls live inside the component
bindActionCreators Not needed; call dispatch(action())

Migrating a connected function component is mostly mechanical. Do it one component at a time; connect and hooks work together in the same app and share the same store.

Reading legacy Redux code

You will also meet older patterns outside React-Redux:

  • Action type constants: export const ADD_TODO = 'ADD_TODO', imported by creators and reducers. Toolkit generates types, so new code does not need them.
  • Switch reducers with spread copies: replaced by createSlice and Immer. They are valid reducers and can sit in the same store as slices.
  • createStore and applyMiddleware/compose: replaced by configureStore with its middleware and enhancers callbacks.
  • Hand-written thunks with redux-thunk as a separate package: Toolkit includes thunk by default.
  • Normalisation with the normalizr package: Toolkit's createEntityAdapter covers many cases.
  • redux-saga and redux-observable: still valid, and common in large older apps; for new apps thunks, listener middleware and RTK Query cover most needs.
  • redux-devtools-extension package: not needed with configureStore.

A safe migration order for an old codebase: (1) switch createStore to configureStore (reducers unchanged), (2) convert one reducer at a time to createSlice, (3) replace connect with hooks as you touch components, (4) move data fetching to RTK Query later. At every step the app keeps working.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which components can only use Redux through connect?

    Hooks cannot be used in class components, so connect is how a class receives store data.
  2. 2. In connect, what does an object passed as mapDispatchToProps do?

    The object shorthand binds each action creator to dispatch, giving you function props like onAdd.
  3. 3. How does connect decide whether to re-render?

    If every prop returned by mapStateToProps is === to the previous one, the wrapped component is not rendered again.
  4. 4. Which is NOT a recommended first step when migrating legacy Redux?

    Because connect, hooks and old reducers all work together, you can migrate gradually and keep the app working.

Summary

  • connect(mapState, mapDispatch)(Component) passes state and action functions to a component as props; it re-renders on shallow prop changes.
  • It is the only option for class components and is common in legacy code; new code should use hooks.
  • mapStateToProps becomes useSelector, mapDispatchToProps becomes useDispatch.
  • Legacy patterns (constants, switch reducers, createStore, separate thunk package) all still work and migrate gradually to Redux Toolkit.
  • connect, hooks and hand-written reducers can coexist in one store during a migration.

Next: Async Logic and Thunks