Which HOC will wrap the other. Does the order of wrapping with multiple HOCs matter in react or not? I have created multiple HOCs withSocket, withLoadin
Does the order of wrapping with multiple HOCs matter in react or not?
The order in which you wrap the HOCs matters because of the props that are passed on from one HOC to its child component. Consider the following example
const mapStateToProps(state, props) {
console.log(props.match);
return {
match: props.match
}
}
First case:
withRouter(connect(mapStateToProps)(App));
In this case since the withRouter
wraps the connect
, the props provided by withRouter ie history, match etc
will be available in mapStateToProps
used by connect.
Think of an HOC like
const MyComponent = connect(mapStateToProps)(App);
export default withRouter(MyComponent);
where withRouter
could be implement like
const withRouter = (Comp) => {
return class Something extends React.Component {
render() {
return
}
}
..
}
and so in this case, the Comp
i.e MyComponent
which is wrapped with withRouter
receives the match props, which in the above case is the component being wrapped by connect
Second case:
connect(mapStateToProps)(withRouter(App));
In this case since the connect wraps the withRouter, the props provided by withRouter
ie history, match etc
will not be available in mapStateToProps
used by connect
if they are not provided by the parent.
Should I be worry about deep ugly nesting?
you should only worry about it if the props provided by one HOC is being used by another. Say if you use passed down props from HOC directly inside the base component, you won't need to worry about the order
Will it make an impact on performance of component?
The order of using HOC doesn't affect a components performance
Check the below codesandbox for an example