Samuel
Samuel

Reputation: 2635

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?

Upvotes: 12

Views: 10647

Answers (2)

The Reason
The Reason

Reputation: 7973

I wouldn't use that. It's complicated to understand where the props come from, when you are looking at your MyComponent component. There are much more downsides using this pattern. Anyway if you decided to use HOCs use it in a right way e.g.

const withDetails = Component => {
  const C = props => {
    // do something
  }

  // assign display & wrapped names - easier to debug
  C.displayName = `withRouter(${Component.displayName))`
  C.WrappedComponent = Component;

  return C;
}

Instead of using HOCs i suggest looking at render props react pattern. It's well explained in a Use a Render Prop! article by Michael Jackson (react-router creator).

Hope it makes sense.

Upvotes: -6

klugjo
klugjo

Reputation: 20885

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.

Upvotes: 9

Related Questions