1

I've been looking into the concept of HOC's, but I'm not sure how to have multiple without just having an ugly deep nesting.

For example, if I wanted to add a library's HOC, like Redux provider or Apollo provider, then have my own HOC's and so on. Like below, is this not just really inefficient and ugly?

(Just an example, not actually using doing this at the moment. All theoretical.)

ReactDOM.render(
    <ApolloProvider client={ client }>
        <ReduxProvider state={ state }>
            <MyHOC xyz={ abc }>
                <App />
            </MyHOC>
        </ReduxProvider>
    </ApolloProvider>,
    document.getElementById('root')
)

As compared to

ReactDOM.render(
    <CombinedHOCs client={ client } state={ state } xyz={ abc }>
        <App />
    </CombinedHOCs>,
    document.getElementById('root')
)

But the only way I can think of this is looping through supplied HOC's which would again still have to loop (e.g. map) through everything (depending on what HOC does).

So am I looking at this the wrong way or is there no way to avoid this, assuming that those HOC's would be needed for the given component?

sparcut
  • 795
  • 1
  • 10
  • 27
  • 1
    I don't think there is anything wrong with doing this at all. It's also nice to disguise the providers outside of your App like you've probably done so you'll never see them once you've done the setup. When using actual HoCs functions `hoc1(hoc2(Component))` you'll end up doing the same but you can also use compose so you aren't nesting everything. – Matt Derrick Sep 07 '17 at 11:07
  • You can add some sugar by using compose or flow, an elegant solution is provided by recompose: https://github.com/acdlite/recompose – Braulio Jul 31 '18 at 08:27

1 Answers1

1

I think it's ok to nest HOC like you did in the example. But if you're using redux and Apollo you should integrate it and keep data in one store. You'll get rid of one nesting and this will let you better track the different events that happen in your app.

ReactDOM.render(
    <ApolloProvider store={store} client={client}>
      <MyHOC xyz={abc}>
        <App />
      </MyHOC>
    </ApolloProvider>,
    document.getElementById('root')
)
mradziwon
  • 1,206
  • 1
  • 9
  • 13
  • Yeah, they were the two that came to mind. I've moved to native state, Redux was _too_ optimized, my app didn't really need such a complex state. Especially considering moving to Apollo, with its management & cache of data. – sparcut Sep 07 '17 at 12:52