Does order in which you wrap component with connect and withRouter matter

前端 未结 2 597
北恋
北恋 2021-02-07 14:49

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

相关标签:
2条回答
  • 2021-02-07 15:31

    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 <Comp match={this.context.router.match} />
          }
        }
        ..
    }
    

    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

    0 讨论(0)
  • 2021-02-07 15:48

    React is all about composition and in the majority of cases it shouldn't be a performance problem at all. Don't worry about it until you actually perceive a performance issue. Nesting HOC's is also fine. The only thing you need to take into consideration is when one of the HOC's consumes props injected by another HOC. This is e.g. the case when you need react-router url params in your mapStateToProps to select an object by id. Then you need to apply first the connect() HOC and only then the withRouter() HOC to access the match object in the ownProps of the wrapped component.

    0 讨论(0)
提交回复
热议问题