If you truly want a global variable (not advisable, of course) then you're always 100% free to do

window.globalVar = 0;

in any of your modules.


The more robust solution would of course be to have this global variable sit in some sort of dedicated module, like

globalVar.js

export default {
    value: 0
};

and then you could

import globalVal from './globalVar';

globalVal.value = 'whatever';

from any modules needed.

The only risk would be that webpack might duplicate this same "global" value into multiple bundles if you're code splitting, depending on your setup. So separate module would be using their own local copy of this not-so-global variable. EDIT - this isn't true. webpack never did this; that comment was based on a misunderstanding on my part.

Answer from Adam Rackis on Stack Overflow
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.

Discussions

Is there any way in react, where we have some global variable in a file and after that build we can change those variables and the app works smoothly ?
Sounds like a state variable that you can put in a Context, or a data store (Reudx/Zustand). More on reddit.com
๐ŸŒ r/react
19
0
December 21, 2022
How to declare global variables to be used throughout the app?
Declare them in a file (named in a way that makes sense to you, and in a location that makes sense), then import the JSON vars wherever you need to reference them. More on reddit.com
๐ŸŒ r/reactjs
6
3
July 10, 2016
How to declare global variables in React JS
Then, to make sure it is executed when project initialized. For example, import the file in index.js: ... 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.name. More on stackoverflow.com
๐ŸŒ stackoverflow.com
September 7, 2018
Global Variables
Join the Reactiflux Discord (reactiflux.com) for additional React discussion and help. ... Is there any reason why anyone would store global variables for anything in a JS file somewhere in your application when you have something like Redux or Context API made available to you? More on reddit.com
๐ŸŒ r/reactjs
8
2
April 18, 2022
Top answer
1 of 2
2

Quite a lot of clarifications are required to explain what happens in your code but i'll try to be succinct.

Having it your way

global.js

Is not really global but a module, and exported members are read-only.

You could make it work by exporting an object:

export let myGlobal = { count: 0 };

And changing your onClick handler to

() => { myGlobal.count++ }

But your components won't re-render, since it's not part of the state, and therefore the change won't be noticed by React.

The React way

If you want to share state between components - you should either lift the state up or use the context API as described in this answer

2 of 2
1

In raw javascript project, you can export a global variable in a file, and import anywhere in other files. That's what you did.

But in React, if you want to use a global state, you should use context API. Your code does not run because myGlobal is not declared as a state. Thus, React cannot track its state.

The correct method is like this:

const {useState, useContext} = React;

// you can create context outside of React component
const CounterContext = React.createContext(0);
// export default CounterContext;


// import CounterContext from 'global/counter-context';
const ChildComponent = () => {

   const counter = useContext(CounterContext);
   
   return (
     <div className="other-component">
     <p>This is Child Component that consumes CounterContext value </p>
     <p>Current counter is: {counter}</p>
     </div>
   );

};

// import CounterContext from 'global/counter-context';
const App = () => {
  const [counter, setCounter] = useState(0);
  return (
      <div className="app">
      <CounterContext.Provider value={counter}>
         <p>This is Context Provider component. Global state is maintained here and you can consume the state value in any other child components</p>
         <label>Click this button to increment global counter state: </label>
         <button onClick={() => setCounter((oldCounter) => (oldCounter + 1))}>
           Increment
         </button>
         <ChildComponent />
      </CounterContext.Provider>
      </div>
    );
};

class Root extends React.Component {
  render() {
    return (<App />);
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
.app {
  border: 1px solid red;
  padding: 5px;
  margin: 5px;
}

button {
  margin-bottom: 5px;
  margin-left: 5px;
}

.other-component {
  border: 1px solid blue;
  padding: 5px;
  margin: 5px;
}
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<div id="root">
</div>

Hooks API Reference

๐ŸŒ
Medium
medium.com โ€บ nerd-for-tech โ€บ get-global-variables-in-react-js-490cf68f2a73
Get global variables in React JS
August 10, 2021 - 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> ) }
๐ŸŒ
GitHub
github.com โ€บ donnikitos โ€บ react-useGlobal
GitHub - donnikitos/react-useGlobal: A React.js hook to share and use global variables between unconnected components. ยท GitHub
import React from 'react'; import useGlobal from '@donnikitos/react-useglobal'; // use in Component export default function Comp(props) { const [globalX, setGlobalX] = useGlobal('x'); // Access global variable x const [globalY, setGlobalY] = useGlobal('y', 'Hello World'); // Access global variable y and set initial value to string 'Hello World' const [tryY, setTryY] = useGlobal('y', 'test me'); // Access global variable y, second argument will be ignored React.useEffect(() => { setGlobalX('i am global'); // change global variable }, []); return (<div> {globalX} {/* output: i am global */}<br /> <br /> {globalY} {/* output: Hello World */}<br /> {tryY} {/* output: Hello World */}<br /> </div>); };
Author ย  donnikitos
๐ŸŒ
Reddit
reddit.com โ€บ r/react โ€บ is there any way in react, where we have some global variable in a file and after that build we can change those variables and the app works smoothly ?
[Mature Content] r/react on Reddit: Is there any way in react, where we have some global variable in a file and after that build we can change those variables and the app works smoothly ?
December 21, 2022 - You could, for instance, have a headless Wordpress (though I prefer Strapi or Supabase) and just pull from an api, then you can just change the value (or add, edit, & delete) elements from that collection and your React app will still pull the latest info without having to rebuild. Of course, that's assuming you're not caching ... Ya this answer is well intentioned but not what you are looking for in this exact specific case, I think. see u/raaaahmanโ€™s answer! ... not with a database or cms, if you had the variables in a local data file within the project you would need to rebuild
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ react โ€บ global variable in react
Global Variable in React | Delft Stack
January 27, 2022 - # react const globeVar = "I am a Global Variable"; export default globeVar; Now that we have exported our variable, it will work as a global variable. We can import this file into any file and use it as a global variable.
๐ŸŒ
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 - 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 ... Senior Full Stack at Pixium Digital Pte Ltd. ... Simply use the environment variables it is build for that: create-react-app.dev/docs/adding-c...
Find elsewhere
๐ŸŒ
Create React App
create-react-app.dev โ€บ docs โ€บ using-global-variables
Using Global Variables | Create React App
October 24, 2019 - When you include a script in the HTML file that defines global variables and try to use one of these variables in the code, the linter will complain because it cannot see the definition of the variable.
๐ŸŒ
sebhastian
sebhastian.com โ€บ react-global-variable
Declare React global variable with code examples | sebhastian
July 7, 2022 - One way to declare a global variable in React is to attach a new variable as the property of the window object. For example, create a window.name variable in the index.js file like this:
๐ŸŒ
Quora
quora.com โ€บ Can-we-access-a-global-variable-in-other-files-in-JavaScript
Can we access a global variable in other files in JavaScript? - Quora
Answer (1 of 4): Yes . Any global defined by any code on the page is accessible to any code on the page. However, it needs to have been defined prior to its first use. Say you want to use a variable named gbl_username.
๐ŸŒ
Reddit
reddit.com โ€บ r โ€บ reactjs โ€บ comments โ€บ u6473d โ€บ global_variables
Global Variables : r/reactjs
April 18, 2022 - Join the Reactiflux Discord (reactiflux.com) for additional React discussion and help. ... Is there any reason why anyone would store global variables for anything in a JS file somewhere in your application when you have something like Redux or Context API made available to you?
๐ŸŒ
DhiWise
dhiwise.com โ€บ post โ€บ how-to-use-react-global-variables-a-comprehensive-guide
Enhancing React Applications with Global Variables
June 10, 2024 - In the world of React, a react global variable is a variable that is accessible throughout the entire react app, regardless of the component tree structure. These variables provide a way to store and pass data across many components, from the ...
๐ŸŒ
Medium
medium.com โ€บ @Carmichaelize โ€บ react-importing-global-variables-from-the-window-object-b7db6665651d
React โ€” Importing Global Variables from the Window Object | by Scott Carmichael | Medium
November 3, 2017 - This allows the variable to be used as a module more in keeping with the ES6 approach and can be imported into project files when needed. The benefit of this approach is not having to rewrite (or replace) code that utilises the window object in order to maintain an ES6 coding standard in the project. You can import it and use it like you would a custom component or service class. Its also a useful way to get around stricter React CLIs and compilers throwing errors when using undeclared global variables.
๐ŸŒ
Medium
medium.com โ€บ @toshvelaga โ€บ using-global-css-variables-in-react-js-216f03fcdc56
Using Global CSS variables in React JS | by Tosh Velaga | Medium
March 7, 2022 - Wanting to write DRY CSS I decided ... some global CSS variables and use them across the app instead of copying and pasting everywhere. This gives us the advantage such that if we need to tweak one of the colors, all we have to do is change the value in one file. First let me provide some background. There are a bunch of different ways to apply styling in a React ...
Top answer
1 of 2
1

Your use case here will be consumed by something outside of React (an Apollo Link), so Context does not make any sense here - Context would make a value available to children in the React tree, but your link is not a child in a React Tree.

Instead you can just export an object and modify that object (you probably cannot reassign it depending on how you import/export it, but you can always modify it).

// index.js
export const globalData = {
  auth: null
}
// anywhere else
import { globalData } from './index.js'

globalData.auth = "foo"

That said, you can only work with global data like this if you are not using SSR. If you are using SSR (e.g. in a Client Component in Next.js), you'd need to find another way of doing that.

In that case, you could use Apollo CLient's defaultContext.

2 of 2
-4

if u want to store a variable globally u can use context api or redux-tool kit here i am giving a rough idea how u can achieve this using context API first Create A folder usually context.. inside this create a file usually name as DataProvider.jsx and do thing like this

import { createContext, useState } from 'react';

export const DataContext = createContext(null);

const DataProvider = ({ children }) => {

const [Client, setClient] = useState([]);


return (
    <DataContext.Provider value={{
       Client, setClient
    }}
    >
        {children}
    </DataContext.Provider>
)

}

export default DataProvider; 

next step u should wrap your app.js like this

import DataProvider from './context/DataProvider';

   function App() {
   return (
   <DataProvider>
     <Home />
   </DataProvider>
   );
}


export default App;

now u can setclient or u can use client data like below

assume u have a file name Client.jsx where u want to set the client data

const { setCleint} = useContext(DataContext)

set the Client data to setClient just as normal state now in similar way u can render the client list anywhere like this

const { Cleint} = useContext(DataContext);
๐ŸŒ
Repeato
repeato.app โ€บ home โ€บ implementing global variables in react native
Implementing Global Variables in React Native - Repeato
December 17, 2024 - Organize in a Separate File: Create a dedicated JavaScript file (e.g., global.js) to define your global variables and import it in your main entry file (e.g., index.js). While global variables offer a quick solution, there are more robust methods to manage state across your application: State Management Libraries: Tools like Redux or Flux provide structured ways to manage state, making your code more predictable and easier to debug. React Context API: This feature allows you to pass data through the component tree without manually passing props at every level.
๐ŸŒ
Byby
byby.dev โ€บ js-global-variables
How to use global variables in JavaScript - byby.dev
You can use global variables across multiple files by attaching them to the global object or by using a module system to import and export variables between files.