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

Answer from King Friday 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.

🌐
Create React App
create-react-app.dev › docs › using-global-variables
Using Global Variables | Create React App
October 24, 2019 - Create React App is deprecated. Read more here. 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. You can avoid this by reading the global variable explicitly from the window object, for example...
Discussions

reactjs - React when to use global variables instead of states - Stack Overflow
I'm putting data loaded from API in a variable declared outside of my function component. I had thought of putting it in a state since it is required to be kept through multiple renders. But I didn... More on stackoverflow.com
🌐 stackoverflow.com
Global variable for react - javascript
You can't really define properties as global in react but you can use a library like redux to have one single state for your entire application where you can access the object from different places. ... I guess you might be right @Alex but if the OP is really talking about completely separate apps, then maybe they just want to write a value to a file. I still don't understand the requirement. ... It is a terrible idea, but probably the best/easiest way to use a global variable ... More on stackoverflow.com
🌐 stackoverflow.com
July 13, 2017
How to manage global variables in React?
I’ve started playing around with React now that it is becoming easier to integrate with Meteor. It seems really cool! I do have a few questions though… How should components be declared? I’ve just been keeping them in separate files under the lib folder and declaring them as globals. More on forums.meteor.com
🌐 forums.meteor.com
0
0
July 7, 2015
How to declare global variables in React JS
I've been searching all over the net, including stack overflow, how to declare global variables in JS React. I have a declared variable called name and I'd like to use this variable in two different More on stackoverflow.com
🌐 stackoverflow.com
September 7, 2018
🌐
DhiWise
dhiwise.com › post › how-to-use-react-global-variables-a-comprehensive-guide
Enhancing React Applications with Global Variables
June 10, 2024 - This can reduce the complexity ... variable in a React component 2const UserProfile = () => { 3 const user = window.myGlobalVariable.user; 4 return <div>Welcome, {user}!</div>; 5};...
🌐
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:
Top answer
1 of 3
6

The reason why you use state instead of a variable outside the component is because of re-rendering.

If you do not use state, the component will not be updated with the new data returned from your api.

In addition, the correct way to use useEffect is as follows (commented), if you intend to update the data only once.

const [ cityList, setCityList ] = useState([]);

function Component(){
    
    useEffects(()=>{      //<-- remove async here as it's not allowed.
        
        const getData = async () => {
              
              const data = await loadCities();
              setCityList(data)

        }
        getData();
    },[]);  //<---- add a empty dependency so it only called once when component mounts
    
    ...
}

We usually use variable outside component if it doesn't change.

const initialData = ['a','b','c']

component A = () => {
      // it's fine to use initialData out of the component because it doesn't change.
}

Of course, there are also times where we can use variable outside the component that can change over time. But only if the rendering of the component does not depend on it. (e.g. using a global variable to track a setTimeout)

2 of 3
2

Yes, don't use that method.

You can set a state to keep the values if they can change:

function Component() {

    const [cityList, setCityList] = useState()
    
    useEffect(async () => {
        if (!cityList) {
            const response = await loadCities();
            setCityList(response);
        }
    }, [cityList]);
    
    ...
}

Check out this example from the React doc: https://reactjs.org/docs/faq-ajax.html#example-using-ajax-results-to-set-local-state

If the data don't change you can declare a variable inside the component:

function Component() {

    const cityList = []
        
    ...
}

The hook useMemo that you have quoted is an optimization. It can be used to avoid unnecesary computations because it stores a memoized value. useMemo is helpful when you have expensive calculations that depends on another values.

Check out the official doc about: https://reactjs.org/docs/hooks-reference.html#usememo

🌐
Reactgo
reactgo.com › home › how to declare a global variable in react
How to declare a Global variable in React | Reactgo
July 20, 2023 - import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; window.$name = 'king' //global variable ReactDOM.render(<App />, document.getElementById('root'));
🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › tech guides & tutorials
How to Use a Globally Defined Script Inside a React Component | Pluralsight
July 31, 2020 - A global variable can be defined as follows. <script> window.user = { id: 3, name: "John Doe", } </script> The window is the global object in the browser environment. Any property attached to the window object can be accessed from any script ...
Find elsewhere
🌐
DEV Community
dev.to › yezyilomo › global-state-management-in-react-with-global-variables-and-hooks-state-management-doesn-t-have-to-be-so-hard-2n2c
Global state management in React with global variables and hooks. State management doesn't have to be so hard. - DEV Community
May 31, 2021 - Here we are going to use useState ... to store global state let count = 0; function Counter(props){ const [,setState] = useState(); let incrementCount = (e) => { ++count; console.log(count); // Force component to re-render ...
🌐
EDUCBA
educba.com › home › software development › software development tutorials › react native tutorial › global variable react native
Global Variable React Native | Global Variable React Native with Example
March 31, 2023 - While using React Native, one can create global scope variables by just adding a global prefix before the variable. In the code below, the major components used for the proper execution are: ... Below, all navigator elements are developed ...
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
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;
🌐
DEV Community
dev.to › yezyilomo › you-can-definitely-use-global-variables-to-manage-global-state-in-react-17l3
You Can Definitely Use Global Variables To Manage Global State In React - DEV Community
July 7, 2021 - With this and a little help from hooks, we'll be able to manage global state completely with global variables. Luckily we won't need to implement this on ourselves because State Pool got our back. State Pool is a react state management library based on global variables and react hooks.
🌐
Savas Labs
savaslabs.com › blog › using-react-global-state-hooks-and-context
Using React Global State with Hooks and Context | Savas Labs
June 25, 2020 - // components/MyComponent.js import { useContext } from 'react'; import AppContext from './AppContext'; export const myComponent = () => { // Get the global variables & functions via context const myContext = useContext(AppContext); // ... component continues · Know React and Want to Learn React Native? Here's Where to Begin · Similarly, child components can update global context using the functions passed down in the context. For example: import React, { useContext } from "react"; import { TextInput } from "react-native"; import AppContext from "./AppContext"; export const MyTextInput = () => { // Get the global variables & functions via context const myContext = useContext(AppContext); return ( <TextInput value={myContext.setting1value} onChangeText={myContext.setSetting1value} /> ); }; There you have it!
🌐
Meteor
forums.meteor.com › help
How to manage global variables in React? - help - Meteor Forum
July 7, 2015 - I’ve started playing around with React now that it is becoming easier to integrate with Meteor. It seems really cool! I do have a few questions though… How should components be declared? I’ve just been keeping them in separate files under the lib folder and declaring them as globals.
🌐
Reddit
reddit.com › r/reactjs › best way to initialise a global variable?
r/reactjs on Reddit: Best way to initialise a global variable?
December 6, 2023 -

Hi i have a package A with some helper functions and UI component, package A exports UI component and helper functions idependent of each other. I am importing this package in a react app. In the package A i want to initialise a global variable based on which I want to modify the behaviour of some helper functions. what is the best way to set that variable from react app? should i create a global config object and pass it from the react app or is there any better way to handle this problem?

🌐
Medium
medium.com › nerd-for-tech › get-global-variables-in-react-js-490cf68f2a73
Get global variables in React JS
August 10, 2021 - 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. It is perhaps the simplest method there is to have global variables.
🌐
4Geeks
4geeks.com › how-to › react-global-context
How to use React Global Context?
July 16, 2025 - You can also use the npx create-react-app command to initialize your project but you should know that this command is getting deprecated by React, instead, I highly recommend you to use Vite.js to initialize your project, this compiler is very fast, efficient and is one of the favorites of the community. Preview of the project. First, initialize your project. ... Once you have initialized the project, we have to create a few components for our application, we will need three components, the first one is App.jsx, in this component will create the global context and store the theme of our application, the second one is Navbar.jsx, in this component we will have the functionality to change the theme from light to dark and vise-versa, and the third one is the Cards.jsx component, this will contain cards with fake products just to better simulate a real application.
🌐
CodePen
codepen.io › Dinir › pen › YqMJLL
react.js take global variables
let stc = 37; let stcc = (n=3) => { stc += n; console.log(stc); } let STT = React.createClass({ getInitialState: function() { return { stA: this.props.tn, stB: this.props.ts, stC: stc } }, getDefaultProps: function() { return { ts: "I am yet happy here.", tn: 47 }; }, stcc: function(n) { stcc(n); this.setState({ stC: stc }); }, render: function() { return ( <div> <span>{this.state.stC}</span> <input type="button" onClick={()=>this.stcc(7)} value="!" /> </div> ) } }); ReactDOM.render( <STT ts={"b"} tn={37} />, document.getElementById("main") );
🌐
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.