React Redux use HOC with connected component

Yes, connect is also HOC and you can nest them arbitrary since a HOC returns a component.

HOC(HOC(...(Component)...)) is OK.


However, I think what you might need is connect(...)(DataSync(YourComponent)) instead of DataSync(connect(...)(YourComponent)) so that DataSync could also access state / props if needed. It really depends on the use case.


I had a very straight forward use case. I wanted to connect my HOC with redux store. In short I wanted to wrap my HOC with redux connect method.

// The HOC
const withMyHoc = (ReduxWrappedComponent) => props => <ReduxWrappedComponent {...props} />

// redux props
const mapStateToProps = (state) => ({});
const mapDispatchToProps = (dispatch) => ({});

// This is important
export default (WrappedComponent) => 
connect(
  mapStateToProps, 
  mapDispatchToProps
)(withMyHoc(WrappedComponent));

There are two many answers in this thread. All of them helped me. Just putting down what actually worked in my case.


Here is a simple example how it works

const AppWrapper = MainComponent =>
  class extends Component{
    componentWillmount(){
      this.props.fetchSomething()
    }
    componentDidUnmount(){
      this.props.push('/')
    }
    render(){
      return (
        <div>
          {this.props.fetchedUsers === 'undefined' ? 
            <div> Do something while users are not fetched </div> :
            <MainComponent {...this.props}/>}
        </div>
      )
    }
  }



const App = ({users}) => {
  // just example, you can do whatever you want
  return <div>{JSON.stringify(users)}</div>
};

// mapStateToProps will be in HOC -> Wrapper
// mapDispatchToProps will be in HOC -> Wrapper

/* you may use DataSync as you want*/
export default connect(mapStateToProps, mapDispatchToProps)(AppWrapper(App))

Useful HOC link


May be this is what you wanted:

DataSync.js

export default connect(mapStateToProps, mapDispatchToProps)(DataSync);

SomeOtherComponent.js

export default DataSync(connect(mapStateToProps, mapDispatchToProps)(SomeOtherComponent));

Use connect on your child components as well. Here is WHY