I am wondering what is the recommended way to communicate between ReactJS components. I took a look at a related question. However, I did not find the answer sufficient. The key approaches seem to be the following:
- Assume that only childs / parents communicate.
- Communication from parent to child is realized by setting props, the reverse is realized by passing a callback as a prop.
This has the following disadvantages:
- Since siblings can't communicate directly, all state which has to be passed back and forth between siblings has to be stored in their common parent. This means that the parent has a lot of state which it doesn't really need.
- Passing callback is rather inelegant.
What I would like to do is to add to components methods / members in order to establish communication. I am thinking along the lines of RxJS
. This would mean the following:
- I accept that communication is out of the scope of functionality handled by ReactJS. This seems to be the case anyhow.
- The members of classes need to be persistent. For example, a parent component should not create a new
during each call to its
function since in this case all the subscriptions would have to be reestablished. Instead the constructor would have to create a
object and in the
this.child = <Child />
My question is: Is component communication somehow handled by ReactJS or is this something that should be taken care of by the developer in some other way?
In the first case: Is there a scalable and elegant way that communication between components can be realized in ReactJS? Is the rationale of the developers of ReactJS is done in the way described above or is there something I am missing?
In the second case: How should the components communicate instead?