If this is just adding BASE_URL, then this can be achieved by declaring it inside a constants.js file and exporting it from there. But then, that makes us do BASE_URL + "something" each time we make a network request which isn't really ideal either. Also there might be some scenarios where other configuration have to be shared, like say, a common header that has to be added to all the requests.

To solve this, most request libraries have in-build solutions. If we are choosing axios as the most popular one, we can create a instance like:

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});
export default instance;

and import this everywhere the axios is going to be used like:

import axios from "./axios-instance";

assuming axios-instance.js is the file where the instance is created. Now you can skip adding the BASE_URL to every request as it is already provided in the instance.

Answer from Agney on Stack Overflow
🌐
DEV Community
dev.to › amirsohel007 › how-can-i-declare-a-global-variable-in-react-app-so-that-i-can-access-it-anywhere-in-the-application-2kjo › comments
[Discussion] How can I declare a global variable in react app so that I can access it anywhere in the application — DEV Community
April 20, 2020 - 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>; There are different approaches to achieve the above: If you use CRA (create-react-app), you might want to read this which comes with a nice way out of the box.
Discussions

How to use global variable in React js?
import React, {useEffect, useState ... }; apiCall(); },[]); return( {temp} ); } export default Weather; I want to use a variable called temp in the return function. But I am not sure how to declare global variables in React... More on stackoverflow.com
🌐 stackoverflow.com
Global Variables in ReactJS - Stack Overflow
We're currently working on a school project and we have a part of the app that's kind of "external". (Just used for displaying a graph) So that /graph folder is now in the /src folder and when comp... More on stackoverflow.com
🌐 stackoverflow.com
December 12, 2017
asynchronous - Use global variable to generate a dynamic url (React Native) - Stack Overflow
I have a datapicker where I select the country and with this I create a url. Elige tu País { More on stackoverflow.com
🌐 stackoverflow.com
January 16, 2020
Define API url in a redux reactjs application - Stack Overflow
Searching around the web but didn't find really an example of explanation for it. Where and how should we define a 'global' api url in a redux application? As we could have many action holders it ... More on stackoverflow.com
🌐 stackoverflow.com
August 25, 2017
🌐
DEV Community
dev.to › amirsohel007 › how-can-i-declare-a-global-variable-in-react-app-so-that-i-can-access-it-anywhere-in-the-application-2kjo
How can I declare a global variable in react app so that I can access it anywhere in the application - DEV Community
April 20, 2020 - 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>; There are different approaches to achieve the above: If you use CRA (create-react-app), you might want to read this which comes with a nice way out of the box.
🌐
GitHub
github.com › react-boilerplate › react-boilerplate › issues › 446
Global Configuration Variables · Issue #446 · react-boilerplate/react-boilerplate
June 1, 2016 - Is there a way to declare the API URL a variable, such as using environment variables? In the example above, I have to declare the API URL statically, which means if deployed to a different server environment (staging, production, etc.), I have to update the API URL manually.
🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › tech guides & tutorials
How to Store and Read Configuration Files Using React | Pluralsight
April 1, 2025 - Now you can access these variables directly using the process.env global object, without adding any import statements. const SERVER_URL = process.env.REACT_APP_SERVER_URL; const CLIENT_ID = process.env.REACT_APP_CLIENT_ID;
🌐
DhiWise
dhiwise.com › post › how-to-use-react-global-variables-a-comprehensive-guide
Enhancing React Applications with Global Variables
June 10, 2024 - This can be achieved by using React hooks like useMemo and useCallback. Environment variables are often used for storing configuration settings and sensitive information. They are defined in .env files and should not be confused with global variables. While global variablesrepresentglobal statewithin thereact app, environment variables` are used for data that should not be included in the source code, such as API ...
🌐
Medium
medium.com › nerd-for-tech › get-global-variables-in-react-js-490cf68f2a73
Get global variables in React JS
August 10, 2021 - 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. Step 2: Create multiple variables in a new file in the above folder ...
🌐
Stack Overflow
stackoverflow.com › questions › 63616074 › how-to-use-global-variable-in-react-js
How to use global variable in React js?
Declare temp as the state variable and you can use it the return method. import React, {useEffect, useState } from 'react'; import axios from 'axios'; function Weather(){ const [temp,setTemp] = useState(""); useEffect(()=>{ const apiCall= async ()=>{ var appid=""; const resp=await axios.get(`http://api.openweathermap.org/data/2.5/weather?q=seoul&appid=${appid}`); console.log(resp.data); setTemp(String((resp.data.main.temp-273)).substring(0,4)); }; apiCall(); },[]); return( <div> <div className="displayTime">{temp}</div> </div> ); } export default Weather;
Find elsewhere
🌐
Medium
a-carreras-c.medium.com › development-and-production-variables-for-react-apps-c04af8b430a5
Using Development and Production Variables for React apps with process.env.NODE_ENV | by Alberto Carreras | Medium
March 9, 2020 - We are also exporting a config constant which contains a conditional (ternary) operator which will return the development or production variable based on the value of the process.env.NODE_ENV global variable (more info about process.env on this post) which is defined when we run our app in development npm start or in production when deployed running npm run deploy. More about process.env.NODE_ENV in the -Create-react-app documentation (thanks Chris Moran for the note). Now, the React components can import the variables: // Component.js import { config } from './Constants'var url = config.url.API_URL var url_users = config.url.API_URL_USERS
🌐
Stack Overflow
stackoverflow.com › questions › 45881562 › define-api-url-in-a-redux-reactjs-application
Define API url in a redux reactjs application - Stack Overflow
August 25, 2017 - I'm not sure what you are exactly trying to do, but I for once declare all my api url's in a file: export const API_URL = 'http://localhost:8080'; and import this url in my files: import {API_URL} from "./path.js"; ... I call the filename RestAPI.js. But you can obviously name it whatever you want. I have 4 URL's in this file, one for each microservice and I import the URL I currently need in my components. But I'm not a reactjs guru and there might be a better solution :)
🌐
sebhastian
sebhastian.com › react-global-variable
Declare React global variable with code examples | sebhastian
July 7, 2022 - If you want global variables that get tracked by React and update your UI according to its changes, then you need to use React Context API instead.
🌐
Reddit
reddit.com › r/reactjs › set global variables
r/reactjs on Reddit: Set global variables
March 2, 2021 -

Consider a simple API call using Axios:

Axios.get(`/api/v1/levels/${this.app.levelID}`)
            .then(response => {
                let data = response.data.data;
            })
            .catch(error => {
                console.log(error)
            });

I struggle to have properties of the data variable available outside the function processing the request. Data has properties such as data.name, data.gravity etc, which will be rendered when I call them within the function, but not anywhere else.

This API call is a part of a React component, and I would like to be able to access these values anywhere within the class after this call has been performed, of course.

I've tried using object properties this.name = data.name; this.gravity = data.gravity;, states: this.setState({name: data.name, gravity: data.gravity}), but nothing seemed to work. As soon as I left the function, though, whatever variable I appended these values to, they all returned undefined. That means that outside the function I would perform a call console.log(this.name) or like this this.state.name, but to no avail.

What am I doing wrong? How can I have data from API accessible as attributes throughout the entire class? Right now, I am using local storage, which is not very convenient and doesn't function properly.

Top answer
1 of 15
159

Beyond React

You might not be aware that an import is global already. If you export an object (singleton) it is then globally accessible as an import statement and it can also be modified globally.

If you want to initialize something globally but ensure its only modified once, you can use this singleton approach that initially has modifiable properties but then you can use Object.freeze after its first use to ensure its immutable in your init scenario.

const myInitObject = {}
export default myInitObject

then in your init method referencing it:

import myInitObject from './myInitObject'
myInitObject.someProp = 'i am about to get cold'
Object.freeze(myInitObject)

The myInitObject will still be global as it can be referenced anywhere as an import but will remain frozen and throw if anyone attempts to modify it.

Example of react state using singleton

https://codesandbox.io/s/adoring-architecture-ru3vt (see UserContext.tsx)

If using react-create-app

(what I was looking for actually) In this scenario you can also initialize global objects cleanly when referencing environment variables.

Creating a .env file at the root of your project with prefixed REACT_APP_ variables inside does quite nicely. You can reference within your JS and JSX process.env.REACT_APP_SOME_VAR as you need AND it's immutable by design.

This avoids having to set window.myVar = %REACT_APP_MY_VAR% in HTML.

See more useful details about this from Facebook directly:

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

2 of 15
91

Why don't you try using Context?

You can declare a global context variable in any of the parent components and this variable will be accessible across the component tree by this.context.varname. You only have to specify childContextTypes and getChildContext in the parent component and thereafter you can use/modify this from any component by just specifying contextTypes in the child component.

However, please take a note of this as mentioned in docs:

Just as global variables are best avoided when writing clear code, you should avoid using context in most cases. In particular, think twice before using it to "save typing" and using it instead of passing explicit props.

🌐
Create React App
create-react-app.dev › docs › using-global-variables
Using Global Variables | Create React App
October 24, 2019 - You can avoid this by reading the global variable explicitly from the window object, for example:
🌐
Reactgo
reactgo.com › home › how to declare a global variable in react
How to declare a Global variable in React | Reactgo
July 20, 2023 - Now, we can access the global variable window.$name from our components like this. ... import React from "react"; function App() { const name = window.$name; console.log(name); // 'king' return ( <div> <h1>{name}</h1> </div> ); } export default App; ... How to define and use environment variables in React appSetting a Default Value to the props in ReactHow to fix the react-scripts command not found ErrorHow to redirect to external URL in React RouterGetting started with GraphQL, Apollo and React hooksHow to set a document title in React