React Not-related Components


The only way if your components does not have a parent-child relationship (or are related but too further such as a grand grand grand son) is to have some kind of a signal that one component subscribes to, and the other writes into.

Those are the 2 basic operations of any event system: subscribe/listen to an event to be notify, and send/trigger/publish/dispatch a event to notify the ones who wants.

There are at least 3 patterns to do that. You can find a comparison here.

Here is a brief summary:

  • Pattern 1: Event Emitter/Target/Dispatcher: the listeners need to reference the source to subscribe.

    • to subscribe: otherObject.addEventListener('click', () => { alert('click!'); });
    • to dispatch: this.dispatchEvent('click');
  • Pattern 2: Publish/Subscribe: you don't need a specific reference to the source that triggers the event, there is a global object accessible everywhere that handles all the events.

    • to subscribe: globalBroadcaster.subscribe('click', () => { alert('click!'); });
    • to dispatch: globalBroadcaster.publish('click');
  • Pattern 3: Signals: similar to Event Emitter/Target/Dispatcher but you don't use any random strings here. Each object that could emit events needs to have a specific property with that name. This way, you know exactly what events can an object emit.

    • to subscribe: otherObject.clicked.add( () => { alert('click'); });
    • to dispatch: this.clicked.dispatch();