How to make a shared state between two react components?

The dependency type between the components will define the best approach.

For instance, redux is a great option if you plan to have a central store. However other approaches are possible:

  • Parent to Child

    1. Props
    2. Instance Methods
  • Child to Parent

    1. Callback Functions
    2. Event Bubbling
  • Sibling to Sibling

    1. Parent Component
  • Any to Any

    1. Observer Pattern
    2. Global Variables
    3. Context

Please find more detailed information about each of the approaches here


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:

function Store(initialState = {}) {
  this.state = initialState;
}
Store.prototype.mergeState = function(partialState) {
  Object.assign(this.state, partialState);
};

var myStore = new Store();

ReactDOM.render(
  <FirstComponent mergeState={myStore.mergeState.bind(myStore)} />,
  firstElement
  );
ReactDOM.render(
  <SecondComponent mergeState={myStore.mergeState.bind(myStore)} />,
  secondElement
  );

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.

Note that you can always pass the store (myStore) itself to the components; it just feels less react-y to do so.

Here is some more documentation that might be of interest:

React Docs: "Communicate Between Components"

For communication between two components that don't have a parent-child relationship, you can set up your own global event system. Subscribe to events in componentDidMount(), unsubscribe in componentWillUnmount(), and call setState() when you receive an event. Flux pattern is one of the possible ways to arrange this.