Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using global variables in Redux App

Tags:

reactjs

redux

In Redux, we can use props as a constant, and state as a global variable. But what do we have to use when we need a global constant?

Below is the options that I can consider.

  1. Just use state and don't change it. We should follow the rule 'single source of the truth'.
  2. Use context. It can be a simple solution but as the official React homepage says, it is an experimental feature, so it can make my app unstable.
  3. Collect all global variables in a single js file and use it like a js module.
  4. Declare npm environment variables from the webpack config file and use them as global constants.
  5. Other ways

Which one would assure the most proper architecture? And can you tell me the reason?

like image 289
Sejin Jeon Avatar asked Feb 21 '18 06:02

Sejin Jeon


2 Answers

I would suggest the Option 3.

Reasons:

  1. Maintainability - You just have to change this file and it will be made available across all the modules that use this so modifying is really easy.

  2. Availability - Since this acts like a separate module it's very easy to import and use it.

  3. Debugging - Compared to other options there isn't much hassle while debugging since everything that is within the module is easily accessible as we wrote it in the first place.

like image 62
Adarsh Avatar answered Nov 17 '22 13:11

Adarsh


I will also suggest option 3.

As you can separate out the global constants at one place and can change them without touching the code. Just need to rebuild the project.

You can use webpack for this. Approach is very simple-

Define your global constants in a file lets say constants.js and export them. Lets say you want to configure API_KEY constant globally

const API_KEYS= {
    production: JSON.stringify('prod-const'),
    development: JSON.stringify('dev-const'),
    test: JSON.stringify('test-const')
};

// based on the node env variable set by you get available environment setting

const environment = function () {
     switch(process.env.NODE_ENV) {
         case 'production':
             return 'production';
         case 'development':
             return 'development';
         case 'test':
             return 'test';
         default:                // in case ...
             return 'development';
     };
};

// Helper method to get const value based on env

const mapEnvToConstants = function (consts) {
     return consts[environment()];
};

// Use webpack to generate the build based on the env variable set // webpack config

module.exports = {
    // ...
    plugins: [
        new webpack.DefinePlugin({
            'const1': mapEnvToConstants(API_KEYS)
        })
    ],
    // ...
}

If you want to point to a different env variable or constant you need to rebuild the project.

like image 22
WitVault Avatar answered Nov 17 '22 11:11

WitVault