How to make a shared state between two react components?

Posted by Prem Tiwari | Updated on

If you want to make a shared state between two react components? What you want is to implement some object that stores your state, that can be modified using callback functions. You can then pass these functions to your React components.

For instance, you could create a store:

Now, both the FirstComponent and SecondComponent instances can call this.props.mergeState({ . . .}) to assign state to the same store. I leave Store.prototype.getState as an exercise for the reader.


If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.

Related Questions & Answers