The connect function creates a Higher-Order Component (HOC) that injects store state into a GlyphUI component’s props. It automatically subscribes to store changes and efficiently updates the component only when the selected state changes.
Optional function to select specific parts of the state. Receives the entire state and returns the subset to inject into the component.Function Signature:
(state) => selectedState
Using a selector optimizes performance by only triggering re-renders when the selected state changes, not the entire store.
connect uses shallow comparison to determine if the component should update:
Primitives: Compared by value (===)
Objects/Arrays: Compared by reference (===)
Functions: Compared by function name
This means you should return consistent references from selectors:
// Bad: Creates new array every timeconst selector = state => ({ items: state.items.filter(item => item.active) // New array reference!});// Good: Return the array reference directly if possibleconst selector = state => ({ items: state.items // Same reference if items didn't change});
The connected component automatically handles subscription lifecycle:
Constructor: Subscribes to store and gets initial state
Updates: Receives new state when store changes (if selected state changed)
Unmount: Automatically unsubscribes via beforeUnmount lifecycle hook
You can still use lifecycle methods in your component:
class MyComponent extends Component { mounted() { console.log('Component mounted with store:', this.props.store); } beforeUnmount() { console.log('Component will unmount'); // Note: No need to unsubscribe from store, connect handles it }}