React Redux connect(): When and How to Use It

Master the connect() function for Redux state management in React applications

React Redux provides multiple ways to connect your components to the Redux store. While the hooks API (useSelector and useDispatch) has become the recommended approach in modern React applications, the connect() function remains a powerful pattern that many developers still encounter in existing codebases.

The connect() function is a higher-order component that wraps your React component and provides a bridge to the Redux store. It abstracts away the subscription logic and automatically handles updates when the store state changes. This pattern was the standard way to use Redux with React for many years before the introduction of hooks in React 16.8 and the subsequent React Redux hooks API.

Understanding how connect() works gives you the foundation to work with both legacy and modern Redux implementations effectively, whether you're maintaining existing applications or building new ones.

What is the connect() Function

The connect() function comes from the react-redux library and serves as a bridge between your React components and the Redux store. When you wrap a component with connect(), you create a container component that is aware of the Redux store state. This container component handles the logic of subscribing to store updates and passing data down to your presentational component as props.

The fundamental purpose of connect() is to eliminate the need for components to directly access the store through the context API. Before connect() was introduced, developers had to manually subscribe to the store and handle update logic, which led to repetitive boilerplate code scattered throughout applications.

The Connection Pattern

The connection pattern separates your components into two categories:

  • Presentational components focus solely on how things look and behave--they receive all their data through props and don't know anything about Redux.
  • Container components handle the Redux connections and pass data and functions down to presentational components as props.

This separation of concerns makes your code more maintainable and easier to test. When you use connect(), you're essentially creating a container component around your presentational component. This pattern aligns well with Atomic Design principles for building scalable component architectures.

Related reading: See our guide on React Router v6 for routing patterns that complement Redux state management.

Understanding mapStateToProps

The first parameter to the connect() function is mapStateToProps, a function that specifies how to extract data from the Redux store state and transform it for your component's use. This function receives the entire store state as its first argument and optionally receives the component's own props as a second argument.

The return value of mapStateToProps becomes an object that gets merged into the component's props:

const mapStateToProps = (state) => {
 return {
 user: state.user,
 isAuthenticated: state.auth.isLoggedIn,
 cartItemCount: state.cart.items.length,
 totalPrice: state.cart.items.reduce((sum, item) => sum + item.price, 0)
 };
};

When the store state changes, mapStateToProps is called again to compute the new props. React Redux then performs a shallow equality check on the returned object's values to determine if the component needs to re-render.

Using ownProps

The second parameter to mapStateToProps allows you to incorporate the component's own props into your state mapping. This is useful when you need to filter or transform state based on props passed from a parent component:

const mapStateToProps = (state, ownProps) => {
 return {
 todo: state.todos.byId[ownProps.todoId],
 isSelected: state.ui.selectedId === ownProps.todoId
 };
};

Understanding mapDispatchToProps

The second parameter to connect() is mapDispatchToProps, which specifies how to provide action dispatching capabilities to your component. This parameter can be either a function or an object.

When mapDispatchToProps is a function, it receives dispatch as its first argument and optionally receives ownProps:

const mapDispatchToProps = (dispatch, ownProps) => {
 return {
 increment: () => dispatch({ type: 'INCREMENT' }),
 decrement: () => dispatch({ type: 'DECREMENT' }),
 setValue: (value) => dispatch({ type: 'SET_VALUE', payload: value }),
 onSubmit: (formData) => dispatch(submitFormAction(formData))
 };
};

Object Shorthand Form

When mapDispatchToProps is an object, each key-value pair should be an action creator. React Redux automatically wraps each action creator with dispatch:

const mapDispatchToProps = {
 increment,
 decrement,
 setValue,
 onSubmit: submitFormAction
};

This object form is generally preferred for simple cases because it's more concise and equally functional for most use cases.

The connect() Function Signature

The connect() function has a flexible signature that allows you to specify which parts of the connection you need. Both mapStateToProps and mapDispatchToProps are optional.

// Connect with both parameters
const ConnectedComponent = connect(mapStateToProps, mapDispatchToProps)(Component);

// Connect with only mapStateToProps
const ConnectedComponent = connect(mapStateToProps)(Component);

// Connect with only mapDispatchToProps
const ConnectedComponent = connect(null, mapDispatchToProps)(Component);

// Connect with no parameters (receives only dispatch)
const ConnectedComponent = connect()(Component);

Understanding this flexibility is important for choosing the right level of connection for each component. Some components might only need to read state, others might only need to dispatch actions, and some might need both.

Common Patterns and Use Cases

Reading Store State

The most common use case for connect() is reading data from the Redux store and making it available to components as props. This pattern centralizes state access in container components, keeping the component tree clean and focused on presentation.

When reading store state, it's important to select only the data your component actually needs. Selecting more data than necessary can cause unnecessary re-renders when other parts of the state change.

Dispatching Actions

Components that need to trigger state changes use mapDispatchToProps to receive action dispatching functions as props. This pattern keeps action dispatching logic organized and testable.

Combining State and Actions

Many components need both to read state and dispatch actions. In these cases, you provide both mapStateToProps and mapDispatchToProps to connect().

This combination is particularly powerful for form components, user interaction handlers, and components that need to both display state and modify it based on user actions. When handling form state and user inputs in React, be aware of security implications--learn about dangerouslySetInnerHTML and proper XSS prevention in your Redux implementations.

Explore more React patterns in our Complete Guide to React Refs.

Connect vs Hooks: useSelector and useDispatch

With React 16.8 and the introduction of hooks, React Redux added the hooks API as an alternative to connect(). The useSelector hook extracts data from the store, and the useDispatch hook provides access to the dispatch function.

Performance Considerations

The connect() function performs shallow equality checks on the props it computes to prevent unnecessary re-renders. This optimization happens automatically.

With useSelector(), you have more control but also more responsibility. You need to ensure your selectors return stable values or use React.memo() on components to prevent excessive re-renders.

Testing Differences

Components created with connect() separate their Redux logic from their presentation logic. This separation makes testing easier because you can test the presentational component in isolation by passing props directly.

With hook-based components, the Redux logic is embedded within the component itself. Testing requires either mocking the Redux hooks or setting up a full Redux store with test data.

For a comprehensive comparison, see the official React Redux hooks documentation.

When to Use connect() in Modern Code

While the hooks API is now the recommended approach for new code, understanding connect() remains valuable for several reasons. You'll encounter it frequently in existing codebases and third-party libraries.

The connect() function is particularly useful when you want to clearly separate container and presentational components, when you need the automatic performance optimization it provides, or when you're working with class components that can't use hooks.

For new projects starting today, using hooks (useSelector and useDispatch) is generally the better choice. However, connect() remains a valid and sometimes preferable option depending on your specific requirements, team preferences, and existing code patterns.

If you're building a new React application and want to explore modern state management approaches, learn about our React development services to see how we implement these patterns in production applications.

Best Practices

When using connect(), follow these best practices to maintain clean, performant code:

  • Select only the state your component needs - Avoid subscribing to large portions of the store
  • Use memoized selectors (Reselect) for derived data to prevent unnecessary recalculations
  • Keep mapStateToProps functions focused and single-purpose
  • Prefer the object shorthand for mapDispatchToProps when you don't need custom dispatch logic
  • Name your connected components clearly (e.g., "ConnectedUserProfile") to indicate they're connected to Redux

Consider using Reselect for creating memoized selectors that can be reused across multiple mapStateToProps functions. Reselect selectors are efficient because they only recompute when their inputs change, and they maintain the same reference for unchanged results.

For building accessible React applications, complement Redux state management with Radix UI for unstyled, accessible component primitives.

Common Questions About React Redux connect()

Ready to Build Better React Applications?

Our team specializes in React development and can help you implement effective state management patterns.

Sources

  1. React Redux Official Documentation - Connect API - Primary reference for connect() API
  2. React Redux Official Documentation - Hooks API - Official hooks reference
  3. LogRocket - React Redux Connect Tutorial - Practical examples and code patterns
  4. Sam Dawson - useSelector vs connect - Performance and testing comparison