Controlling state between two React child components

Jen-Hsuan Hsieh (Sean)
A Layman
Published in
4 min readMay 25, 2019

--

Copy right@A Layman

I encountered an interesting issue recently. There is a diagram of the interaction of React components.

Copy right@A Layman

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:

  1. Use Singleton pattern
  2. Use props callback
  3. Use ref callback

The below diagram is my implementation.

Copy right@A Layman

There are some points in this diagram.

  1. Child 2 has a private function to set state for itself.
  2. 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.
  3. The child 1 class has a props function. This function wraps the ref instance’s setting…

--

--

Jen-Hsuan Hsieh (Sean)
A Layman

Frontend Developer🚀 Angular • React • Nest • Electron • Micro-frontend • Monorepo Architecture • https://daily-learning.herokuapp.com/