Get global variables in React JS

Get global variables in React JS

·

9 min read

React Logo
Let's suppose you are making an app that makes a lot of requests to the backend at http://localhost:3000. Now you move to production build, and the URL is changed to https://yasharyan.com after hosting it on whatever hosting service you are using. Imagine the pain of going to every line you have used the localhost URL and changing it to the new URL. Wouldn't it be nice if you would have coded smart and used a global variable to just type this:
${URL}/server-time-up/UTC/

There are so many ways you can create Global Variables in React JS that can be accessed in every component of your web app. I am going to tell you about the most common and easy ones.

Using ContextAPI

Context provides a way to pass data through the component tree without having to pass props down manually at every level. The best part about it is that there is no need for external dependencies to be installed. Context is bundled with React. It has a simple approach. Let's say you have many components that want to use a common variable. Rather than keep passing it as a prop from the parent component, it can easily be imported from the Context.

How to do it?

For easily readable code, it's better to create a context directory in the src folder of your react app. Then create a CONTEXT_NAMEContext.js file in that folder. Sample directory structure for context There is no restriction on how many contexts you can have in a project. In fact, you can have a dedicated context for each functionality your app wants to use Context for. The code for creating a Context looks like this:

import React, { createContext, useState } from 'react'
export const SampleContext = createContext()
const SampleContextProvider = (props) => {
    const [variableOne, setVariableOne] = useState('somethingRandom`)
    const Url = "http://localhost:3000"
    return (
         <SampleContext.Provider 
            value={{
                variableOne,
                Url
             }}>
               {props.children}
         </SampleContext.Provider>
    )
}
export default SampleContextProvider

Notice that all the variables (and even functions) that need to be made global are passed down as values in the return statement. Now that the Context was exported, it's time to import it into the components. First, go to your App.js file and wrap all the components you want to access the context. All child components will automatically inherit the context.

   import React, { Fragment } from 'react'
   import Component_One from './Component_One'
   import Component_Two from './Component_Two'
   import Component_Three from './Component_Three'
   import SampleContextProvider from '../contexts/SampleContext'
   const mainComponent = () => {
      return (
        <Fragment>
            <h1>This is a sample component</h1>
            <SampleContextProvider>
                <Component_One />
                <Component_Two />
                <Component_Three />
            </SampleContextProvider>
        </Fragment>
      )
   }

Notice how all imported components were wrapped with <SampleContextProvider>? All these components now have access to all the values in the context. To access (consume) them, you'll have to do the following:

import React, { Fragment, useState, useContext } from 'react'
import SampleContext from '../contexts/SampleContext'
import axios from 'axios'
const Component_One = () => {
    const { variableOne, Url } = useContext(SampleContext)
    const [getServerTimeUp, setServerTimeUp ] = useState()
    axios.get(`${Url}/server-time-up/UTC/`)
    .then(res => {
       setServerTimeUp(res.data.time)
    }
    return (
        <Fragment>
             <h1>This is the value of variableOne: {variableOne}</h1>
             <p>{getServerTimeUp}</p>
        </Fragment>
    )
}

This way, you can globally set and get variables in whatever component you need.

Using .env file

If you have used NodeJS, you've probably used or heard of .env files. Let's get that feature on your React app.

Case 1: Using create-react-app

If you are using the create-react-app to quickly set up your React app, your work to add a .env file is already half done.

  • Step 1: Create a .env file in the root of your React app Env file in React
  • Step 2: Start typing the variables in the .env file. Remember that you need to start each variable with a REACT_APP_ for it to work; otherwise, your variables will not be imported.
    REACT_APP_DATABASE=redis
    REACT_APP_FIRST_RELEASE=02Nov2019
    REACT_APP_LAST_UPDATE=07Dec2020
    
  • Step 3: Import them into your component using process.env.REACT_APP_.
    render() {
    return (
      <div>
           <h1>
              We are using {process.env.REACT_APP_DATABASE}
           </h1>
      </div>
    );
    }
    

Case 2: Not using create-react-app

If you are into having more control over your project and writing webpack by yourself, you'll need to do a few more steps to set up .env support.

  • Step 1: Install dotenv package in your project using npm install dotenv or yarn install dotenv
  • Step 2: Import the file into your index.js file if you need support in all components or just in a particular component if you want it to be otherwise. require('dotenv').config()
  • Step 3: Now, you can follow the same process in Case 1 to get your environment variables set up. You do not need to start every variable with REACT_APP_ if you are not using create-react-app.

    Exporting manually from a .js file

    It is perhaps the simplest method there is to have global variables.
    • Step 1: Go to your src folder and create a new folder called constants or whatever you want to name it. exporting variables manually
    • Step 2: Create multiple variables in a new file in the above folder like global.js and then export them so that they can be imported into other components.
const Url = 'http://localhost:5000'
const themeDefault = 'dark'
const namesOfModes = ['dark', 'moonlight', 'eclipse', 'light']

export { Url, themeDefault, namesOfModes }
  • Step 3: Now it is time we import these constants in our components
import React from 'react'
import { Url, themeDefault, namesOfModes } from '../constants/global'
const Component_Three = () => {
  return (
     <div>
       <h1>Current Theme: {themeDefault}</h1>
       <p>Homepage: {Url}</p>
     </div>
  )
}





Note: You'll argue that you can use packages like Redux and RecoilJS, but let me remind you that they are state management tools, and they should not be used just to store global constants.

Thanks

Hope you found this article informative and intriguing. If it helped you, do give it a like 🧡 and share it with people who might find it useful. Also check out my Instagram and Facebook pages for more content. Buy Me A Coffee

Did you find this article valuable?

Support Yash Aryan by becoming a sponsor. Any amount is appreciated!