DEV Community

Muhammad Awais
Muhammad Awais

Posted on

The simplest way to share data between two unrelated Components in react

There are following ways of component communication in react:

  1. From Parent to Child using Props
  2. From Child to Parent using Callbacks
  3. Between Siblings :
    1. Combine the above two methods
    2. Using Redux
    3. Using React’s Context API

But, What if you don't want to use the context API hook?
What if you want to minimize API calls from listing to detail components?
What if you want the communication of unrelated components?

Here comes the service that actually holds data on the trigger and passes it to the desired data requested components.

you have to make a shared service, using exported class in react,

class dataHolding {

    constructor() {
        this.data = {};
    }

    getData(data) {
        this.data = data;
        console.log(data);
    }

    setData() {
        return this.data;
    }

}
export default new dataHolding;
Enter fullscreen mode Exit fullscreen mode

calling dataHolding service to store data,

// Component A
this.dataHolding.getData(data);
Enter fullscreen mode Exit fullscreen mode

calling dataHolding service to retrieve data from service anywhere,

// Component B
let details = this.dataHolding.setData();
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
nagarajanprince profile image
nagarajanprince

Hi,

I have a question regards this.if I am wrong sorry.i am new in react, the question is without import component how you can access methods above example

// Component A
this.dataHolding.getData(data);

// Component B
let details = this.dataHolding.setData();

can you please give Component A code

Collapse
 
muhammadawaisshaikh profile image
Muhammad Awais • Edited

absolutely as you said, after import I got the access to call the method of that class in the component. without we can't use the class or component in other component.

Collapse
 
muhammadawaisshaikh profile image
Muhammad Awais

Using Rxjs Subscribers way the service will look likes:

import { Subject } from 'rxjs';

const subject = new Subject();

export const dataService = {
setData: d => subject.next(d),
clearData: () => subject.next(),
getData: () => subject.asObservable()
};