How to create global variables in React

Let's learn how to make variables global in React

Posted on November 16, 2020

When you need to make a variable with global scope in React, you can do it in two different ways.

Attaching global variable to window object

One is that you attach a new variable as the property of the window object. For example, create a variable on index.js like this:

import React from "react";
import ReactDOM from "react-dom";
import App from "./App"; = "John"

const rootElement = document.getElementById("root");
  <App />,

And then call the variable on the App.js file:

import React from "react";

export default function App() {
  return (
    <h1>Hello {}</h1>

Although it’s not required, you can prefix the variable name with the dollar sign ($) to identify it as a global variable:

window.$name = "John"

Using environment variables

When you bootstrap your application using Create React App or Next.js, your application will automatically load a .env file that you’ve written:


To call on the environment variable, use the process.env.{ your variable name } syntax:

export default function App() {
  return (
    <div className="App">
      <h1>Hello {process.env.REACT_APP_NAME_VARIABLE}</h1>
      <h2>Start editing to see some magic happen!</h2>

For further information, you can look at the documentation of Create React App or Next.js.

Unlike state and props, the global variables you declared inside window or process.env object won’t be tracked for change. They are good for variables that have constant value and never change through the lifetime of your application.

If you want global variables that gets tracked by React and update your UI according to its changes, then you need to use the Context API.

Related articles:

Level up your React skill today 🔥

Build FOUR projects using React with my latest book.

Structured knowledge from beginner to experienced level!

Learn more
Digesting React Book