React: access to the state of children anti-pattern?

I have a component that at some point should read a state variable belonging to its descendant.
Should this particular state variable move to the parent and be changed via a callback?

As I can see, and some of them are most likely incorrect, this is for and against moving the state to parents:

Pro: This seems to be more suitable for unidirectional data flow mantras.

Con: Other parent elements of the parent will be overwritten when the state changes (not in the real DOM, but it can still affect performance).

What is the best practice here?

+5
source share
2 answers

Best practices for data streams:

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

eg.

<Child onEvent={this.handleEvent}> 

The parent has:

 handleEvent: function(dataFromChild) { } 
+10
source

As Petka noted, the state should live on top.
Thinking in real life explains this well.

The other child elements of the parent will be overwritten when the state changes (not in the real DOM, but it can still affect performance).

You are unlikely to notice this unless you do it at 60 frames per second.
And if you do, React you have an additional shouldComponentUpdate (and PureRenderMixin ).

+2
source

Source: https://habr.com/ru/post/1210694/


All Articles