MENU
Maximizing Composability
To maximize composability, we can use a higher-order function that returns a higher-order component:
RESETRUNFULL
const enhance = connect(commentListSelector, commentListActions);const ConnectedComment = enhance(CommentList);
function connect(mapStateToProps, mapDispatchToProps) {
return function (WrappedComponent) {
return class extends React.Component {
render() {
return (
<WrappedComponent
{...this.props}
{...mapStateToProps(store.getState(), this.props)}
{...mapDispatchToProps(store.dispatch, this.props)}
/>
)
}
}
} }
Single-argument HOCs whose output type is the same as its input type (Component -> Component) are easy to compose together:
const EnhancedComponent = withRouter(connect(commentSelector)(WrappedComponent)) |
const enhance = compose( withRouter, connect(commentSelector))const EnhancedComponent = enhance(WrappedComponent) |
The compose utility function is provided by many third-party libraries including lodash (as lodash.flowRight), Redux, and Ramda.