Controlling state between two React child components
Published in
4 min readMay 25, 2019
I encountered an interesting issue recently. There is a diagram of the interaction of React components.
The main React component call functions from the parent. They will render correspond child. However, the user will not render them at the same time.
The problem is how to control the child 2’s state from the child 1? The main concepts for solving this problem are:
- Use Singleton pattern
- Use props callback
- Use ref callback
The below diagram is my implementation.
There are some points in this diagram.
- Child 2 has a private function to set state for itself.
- The parent refers to child 2 when it renders. Then the parent class has a function to trigger the ref instance’s setting state function of the child 2.
- The child 1 class has a props function. This function wraps the ref instance’s setting…