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 window.name
variable on index.js
like this:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
window.name = "John"
const rootElement = document.getElementById("root");
ReactDOM.render(
<App />,
rootElement
);
And then call the variable on the App.js
file:
import React from "react";
export default function App() {
return (
<h1>Hello {window.name}</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:
REACT_APP_NAME_VARIABLE = John
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>
</div>
);
}
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.
More about React: