javascriptreactjsecmascript-6

What happens when I add a module to the Global React object?


Is it expensive to add a module to the 'global' within react? I wish to have a module avilable when needed without having to rely upon importing it into each file.

I am adding the following into the 'index.jsx' file:

import axios from 'axios';
global.axios = axios;

then using axios by refering to the global.


Solution

  • By expensive, you probably mean, does it add to the overall file-size or memory usage? No, it does not, unless, for example, you use code splitting and don't extract your common or vendor bundles into a separate file.

    It's best practise to try and not populate the global scope, for two main reasons:

    Your question is not specific to React or ES6. There is no "Global React object". In a browser context, the global scope is the window object; so you would use window.axios = axios;. In a node environment, it would be global.axios = axios;. Setting global variables is very useful in some situations, for example, in testing. When setting up tests to run in node, it's common to set your assertion methods on the global object.

    When you import axios, a single instance is created. You gain nothing from placing a reference to axios on the global scope, but you open up possibilities for bugs. Also, in my opinion, defining your dependencies/imports in each file will help with readability and with intellisense in some editors.

    Libraries which make network requests, like axios, are generally placed in service modules or an API util, not in every module. However, if axios really is integral to your app and you import it in many places, you can use something like ProvidePlugin (if you're using webpack).

    ProvidePlugin

    Automaticlly load modules instead of having to import or require them everywhere.