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

前端 未结 2 589
北恋
北恋 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 
          }
        }
        ..
    }
    

    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

提交回复
热议问题