DEV Community

Amir Sohel
Amir Sohel

Posted on

How can I declare a global variable in react app so that I can access it anywhere in the application

I want to declare a global variable in application where I want to store my API URL and it should accessible for all components

Top comments (3)

Collapse
 
otomer profile image
Tomer Ovadia • Edited

@amirsohel007 That's a great question. Btw you should probably tag #beginners and #javascript too. Anyway, since an API URL may vary between environments:

  1. I would advocate the method of setting this variable as an environment variable.

  2. To make it accessible to your different components, you can create a module that deals with both collecting and accessing all the environment variables in the application.

// ## config.js ##
..
module.exports = {
  endpoint: process.env.API_URL,
};


  // ## myComponent.js ##
  import { endpoint } from './config';

  // Now you could do:
  const MyComponent = () => <h1>{config.API_URL}</h1>;

  // Instead of:
  const MyComponent = () => <h1>{process.env.API_URL}</h1>;
Enter fullscreen mode Exit fullscreen mode

There are different approaches to achieve the above:

  1. If you use CRA (create-react-app), you might want to read this which comes with a nice way out of the box.
  2. Otherwise, you can go through the standard ways using webpack which allows you to do it either with:
    • Using npm scripts to set environment variables
  {
    scripts: {
      "dev": "webpack --env.API_URL=http://localhost:8000 --config webpack.config.dev.js",
    }
  }
Enter fullscreen mode Exit fullscreen mode
  • Using an .env file to set environment variables.
  API_URL=http://localhost:8000
Enter fullscreen mode Exit fullscreen mode

Note: Add the .env file to your .gitignore.

Just in case, you might want to read more about dotenv, cross-env

Collapse
 
crimsonmed profile image
Médéric Burlet

React supports environment variables out of the box. I feel creating a module just for that is a bit much. You simply need to define the .env file and have REACT_APP_MYVARIABLE and react will let you use it anywhere in the app by simply calling:
process.env.REACT_APP_MYVARIABLE

Collapse
 
crimsonmed profile image
MĂ©dĂ©ric Burlet • Edited

Simply use the environment variables it is build for that:
create-react-app.dev/docs/adding-c...

This should be tagged #help