eye_mew
eye_mew

Reputation: 9133

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

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?

Upvotes: 7

Views: 6798

Answers (2)

Dan Abramov
Dan Abramov

Reputation: 268265

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).

Upvotes: 2

Esailija
Esailija

Reputation: 140228

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) {

}

Upvotes: 12

Related Questions