Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Multiple Higher-Order Components

I'm just discovering the amazing benefits of using HOC in my react projects.

My question is there any performance hit for calling multiple HOC functions on a component?

Example

export default withState(withLabel(withTheme(MyComponent)))

This will of course only render one component, however looking at my react dev tools i can see the outputted HOC components three levels deep. Is this something to be wary of or is there a better approach to calling multiple HOC on a component?

like image 511
Samuel Avatar asked Apr 02 '18 07:04

Samuel


1 Answers

Your syntax is equivalent to doing:

<StateProvider>
  <LabelProvider>
    <ThemeProvider>
      <MyComponent />
    </ThemeProvider>
  </LabelProvider>
</StateProvider>

The performance hit will come from how these HOC are implemented. You would probably have to look at each of them.

Example:

  • Theme Provider HOCs usually store a bunch of colors and variables in the React context. So using only one at the very root of your App is enough.
  • One could imagine that your LabelProvider simply adds an extra span before your component, in which case there is little to worry about
  • StateProviders like redux usually inject props in the component just below them so you don't really have a choice but to use them whenever you need state objects.

In conclusion, there are no hard rules. Your main focus should be on understanding what these HOC do and to try to limit unnecessary re-renders of your app.

like image 122
klugjo Avatar answered Sep 20 '22 13:09

klugjo