connect function links your components to global stores, automatically re-rendering them when the store state changes. This eliminates prop drilling and keeps your components synchronized with shared state.
Basic Usage
Connect a component to a store:How connect() Works
Theconnect function:
- Injects store state as
props.store - Subscribes to store changes
- Re-renders the component when state updates
- Automatically unsubscribes when the component unmounts
Parameters
store- The store created withcreateStoreselector(optional) - Function to select specific parts of state
Returns
A higher-order function that takes a component class and returns a connected component.Selecting State with Selectors
Selectors let you choose which parts of the store to expose to your component:Selectors optimize performance by preventing unnecessary re-renders. Components only update when their selected state changes.
mapStateToProps Pattern
The selector function works like Redux’smapStateToProps:
Complete Example
Here’s a complete todo application with multiple connected components:Performance Optimization
Theconnect function includes built-in optimizations:
Shallow Equality Checking
Components only re-render when selected state actually changes:Array Comparison
Arrays are compared by length and reference equality:Function Equality
Functions are compared by name, preventing unnecessary updates:For best performance, select only the state your component needs. The smaller the selection, the fewer unnecessary re-renders.
Lifecycle with Connected Components
Connected components automatically manage subscriptions:Multiple Store Connections
Connect a component to multiple stores by nestingconnect calls:
When to Use connect()
Useconnect() when:
- Sharing state across multiple components
- Avoiding prop drilling through component trees
- Synchronizing multiple components to the same data
- Building reusable components that work with global state
For component-specific state, use local state instead. Only connect to stores when you need shared state.
Next Steps
- Learn about creating stores with
createStore - Review local state for component-specific data
- Explore the createApp pattern for simple applications