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?
Best practices for data flows are:
e.g.
<Child onEvent={this.handleEvent}>
The parent has:
handleEvent: function(dataFromChild) {
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With