Reputation: 2635
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
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 HOC
s 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 HOC
s 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
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:
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