React + Redux binding child component methods to parent or keep them on their own

47 views Asked by At

We have an react redux appl. We have a parent class bound to redux

It is our parent class:

render() {
return (
<div>
<Child1 >
<Child2 >
..


const mapStateToProps = (state, ownProps) => ({
  parentRelatedFooVar: state.parentRelatedFooVar
})

const mapDispatchToProps = (dispatch, ownProps) => {
  parentRelatedFooMethod: () => dispatch(parentRelatedFooMethodAction())
}

export default connect(
  mapStateToProps ,
  mapDispatchToProps
)(Parent)

Now you see we have two children. Children1 has to dispatch its own method, but does not need any binding to state (no mapStateToProps)

Our Child1:

const mapDispatchToProps = (dispatch, ownProps) => {
      child1RelatedFooMethod: () => dispatch(child1RelatedFooMethodAction())
    }

    export default connect(
      null,
      mapDispatchToProps
    )(Child1)

With the same manner we have the child2, it also does not have any mapstatetoprops but has to dispatch its own method child2RelatedFooMethodAction.

Question: We may move the dispatch of child1RelatedFooMethod and child2RelatedFooMethod to the parent component, add these two methods to parent mapDispatchToProps list as following:

mapDispatchToProps of Parent modified:

const mapDispatchToProps = (dispatch, ownProps) => {
      parentRelatedFooMethod: () => dispatch(parentRelatedFooMethodAction()),
     child1RelatedFooMethod: () => dispatch(child1RelatedFooMethodAction()),
     child2RelatedFooMethod: () => dispatch(child2RelatedFooMethodAction())
    }

and of course our child1 and 2 should be rendered as

again the render method of parent:

render () {
return(
<div>
<Child1 child1RelatedFooMethod={this.props.child1RelatedFooMethod} />
<Child2 child2RelatedFooMethod={this.props.child2RelatedFooMethod} />

and we totally remove the connect imports mapDispatchToProps call in both Child1 and Child2 components. Because we did not had any mapstatetoprops before and moved mapdispatchtoprops recently, we do not need to use the connect in the child1 and child2 anymore.

Which aspect is better when considering performance? Acummulate the mapDispatchToProps calls in the parent and keep the children simple without any connect usage or the children should keep their dispatch of mapDispatchToProps on their own?

0

There are 0 answers