Phương Hầu
Phương Hầu

Reputation: 89

React: Should I pass this reference of parent component to child component

I has received a requirement from my boss which is analyzing existing code of my colleagues. I encounter some of weird code like this:

class Parent extends React.Component {
   methodA () { ... }
   methodB () { ... }
   render () {
      <div>
         ...other lines of code
         <Child parent={this} />
      </div>
   }
}

And inside of child component, they use this.props.parent.methodA() and other parent methods like so instead of passing function as props.

I am proposing a rule not to use that pattern. Because that's pretty unreadable and the behaviors of those functions might be sometime unpredictable.

I am wondering besides things which i am talking about, does this pattern could run into any performance issues?

Thanks in advance.

Upvotes: 3

Views: 67

Answers (1)

tlt
tlt

Reputation: 15291

Most usual scenario is when child calls some method from parent on click event, for example. In that case you pass just that method.

<Child doSomethingMethod={methodA} />

and then in Childs render method:

<button onClick={doSomethingMethod} />

I can’t think of an example where child should be aware of parents implementation. In your case, parent should always have methodA and if you ever decide you want to change parent structure, you need to change child as well.

On the other hand, when you pass just a method, your child doesnt care where the parent got that method from. So, its loosely coupled where each component handles itself only and receives only those params from other component that it needs (including functions).

Upvotes: 3

Related Questions