Ad

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?

Ad

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)

https://react-redux.js.org/api/connect#connect-returns

Ad
source: stackoverflow.com
Ad