Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing data across React components

In front-end apps there is often data which needs to be accessed by many components. Routing is one example, another is configuration data, e.g. feature switches, default language, etc.

In an app that isn't using any particular framework, I might share this configuration data across modules using

export class Configuration {

  static getConfig () {
    // get the config from the server
    return axios.get('/config').then(function (response) {
      return response;
    })
  }
}

Then import this class into any module that needs to access configuration data. With some front-end framework, it's obvious how to share such "global" data, e.g.

  • AngularJS - Configuration should be defined as a service that's dependency-injected into any controllers/directives/services that need to access config. data
  • Vue.js - use a mixin

However, when using ReactJS it's not obvious which approach should be used. Possible options are:

  1. A plain-old JavaScript module. Encapsulate the data to be shared as a function/method, and import it into any React components that need to access it. The seems like the simplest approach, but I have the feeling that when writing a ReactJS app everything should be defined as a component, rather than JavaScript classes/functions.

  2. Redux seems to be recommended approach for sharing-state within large apps, but this feels like overkill for smaller projects

  3. Something else?

like image 481
Dónal Avatar asked Feb 24 '26 18:02

Dónal


1 Answers

but I have the feeling that when writing a ReactJS app everything should be defined as a component, rather than JavaScript classes/functions.

I really don't see a reason why everything should be a component in React. If it is just data, you can create a single instance of that JS object say and import that anywhere you need it.

I have used similar thing in my app, where I had a "global" kind of object which was saving different configs etc, and then I was using that in the components which needed that data.

Here is also some more info about component communication in React.

like image 113
Giorgi Moniava Avatar answered Feb 26 '26 09:02

Giorgi Moniava