React: is accessing the state of children an anti-pattern?
reactjs
Solution
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) {
}
Problem
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?