7

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?

eye_mew
  • 8,855
  • 7
  • 30
  • 50
  • It should be moved back up since "back up" is where it's needed. Why is that variable even in the child component if the parent component needs it? – Henrik Andersson Jan 08 '15 at 21:42

2 Answers2

12

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

}
Esailija
  • 138,174
  • 23
  • 272
  • 326
  • Is it smelly to store the data in the parent, but not in its `state`, and just in a class variable, if I know there is no need for rererendering? – eye_mew Jan 08 '15 at 22:55
  • 2
    @eye_mew: I'd say it is. It's okay to store stuff like intervals on instance, but anything that `render` depends upon should go into `state`. Otherwise React won't be able to figure out something changed, and lifecycle methods like `componentDidUpdate` will be kinda useless too (because there won't be any data in `prevState`, for example). – Dan Abramov Jan 09 '15 at 00:51
  • See also: [Thinking in React](http://facebook.github.io/react/blog/2013/11/05/thinking-in-react.html) – Dan Abramov Jan 09 '15 at 00:52
2

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

Dan Abramov
  • 264,556
  • 84
  • 409
  • 511