Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: is accessing the state of children an anti-pattern?

Tags:

reactjs

I've got a component that needs to read a state variable belonging to its child at some point.
Should this particular state variable rather be moved to the parent, and be changed via a callback?

As I see it, and some of this is likely wrong, these are the pros and cons of moving the state to the parent:

Pro: This seems to adhere more to the unidirectional data flow mantra of react.

Con: Other children of the parent will be rerendered on state change (not in the real DOM, but it may still have a performance impact).

What is the best practice here?

like image 955
eye_mew Avatar asked Jan 08 '15 20:01

eye_mew


2 Answers

Best practices for data flows are:

  • From parent to child: via props
  • From child to parent: via handlers
  • From unrelated component to another: via message bus

e.g.

<Child onEvent={this.handleEvent}>

The parent has:

handleEvent: function(dataFromChild) {

}
like image 200
Esailija Avatar answered Oct 20 '22 00:10

Esailija


As Petka noted, state should live on top.
Thinking in React explains it well.

Other children of the parent will be rerendered on state change (not in the real DOM, but it may still have a performance impact).

You're unlikely to notice this unless you do this at 60fps.
And if you do, React has you covered with optional shouldComponentUpdate (and PureRenderMixin).

like image 39
Dan Abramov Avatar answered Oct 20 '22 00:10

Dan Abramov