Is There Any Reason React Redux Connect Returns A Function And Not A Component Directly?
I am trying to understand more about higher order components and my understanding is the typical pattern is like this:
const HOC = (WrappedComponent) => {
...
return class extends React.Component {
render(){
<WrappedComponent {...this.props} />
}
}
}
Which you could call like this: HOC(CustomComponent)
However many popular libraries including react-redux instead return a function that in turn returns the component:
const connect = (mapStateToProps) => {
...
const storeToPass = mapStateToProps(store)
return function(WrappedComponent) {
return class extends React.Component {
render(){
<WrappedComponent {...this.props, ...storeToPass} />
}
}
}
}
which you would call like this: connect(mapState)(CustomComponent)
My question is why? Is there any reason for this or is it just a preference on pattern? Why couldn't you do this for the connect function?
const connect = (mapStateToProps, WrappedComponent) => {
...
const storeToPass = mapStateToProps(store)
return class extends React.Component {
render(){
<WrappedComponent {...this.props, ...storeToPass} />
}
}
}
And call it like this: Connect(MapState, CustomComponent)
Is there any difference?
Answer
For one thing, connect
accepts (up to) four arguments: mapStateToProps
, mapDispatchToProps
, mergeProps
and options
. https://react-redux.js.org/api/connect#connect
Of course in theory the function signature could have been flipped to connect(Component, mapStateToProps, mapDispatchToProps, mergeProps, options)
.
However, the reason given from the documentation:
you may use the hoc to enable different components to get the same behavior
Their example is giving two different components login/logout actions:
// first call: returns a hoc that you can use to wrap any component
const connectUser = connect(
mapState,
mapDispatch
)
// second call: returns the wrapper component with mergedProps
// you may use the hoc to enable different components to get the same behavior
const ConnectedUserLogin = connectUser(Login)
const ConnectedUserProfile = connectUser(Profile)
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM