props and context are the ways that react has for moving data between components. Built into these are the fact that if you rerender the source component and it has a new value for the prop/context, then the destination component will rerender too. The child component does not need to somehow register an event listener on the props/context, and then set state when the value changes; it's enough that the props/context changed.

If you do a global variable, then yes, it can in principle be available to all components. However, you will need to write code which listens to changes in that global variable (for example, with an event emitter or an observable), and then every component that consumes it will need to set local state when the global value changes, in order to rerender itself.

context only transmits data to wrapped components, while global variables have no such restriction

While you describe this as a restriction, it's sometimes a very useful benefit.

For example, suppose you are making a group of components that need to work together, such as a TabContainer and a TabPanel. They need to share data between themselves. Since context is only available to the wrapped components, the TabContainer can render a context provider, and the TabPanels can access that context. And if there are multiple TabContainers on the page, they won't interfere with eachother.

Or as another example, suppose you have a Theme object that sets the colors for your app. It's provided via context, and your ui components use it to style themselves. But you also want to let the user change the theme, and see a preview of the change. Since the Theme is using context, you can create a new context provider that just wraps around the preview part of your app. Components inside the preview will use the modified theme, while the rest of the app behaves as normal.

In short: you can put your context provider at whatever level makes sense for your needs. If you want it to be global, put it at the top of your component tree and it's global. But if you want something confined to a region, you can do that too. A global variable does not have this flexibility.

Answer from Nicholas Tower on Stack Overflow
Top answer
1 of 1
10

props and context are the ways that react has for moving data between components. Built into these are the fact that if you rerender the source component and it has a new value for the prop/context, then the destination component will rerender too. The child component does not need to somehow register an event listener on the props/context, and then set state when the value changes; it's enough that the props/context changed.

If you do a global variable, then yes, it can in principle be available to all components. However, you will need to write code which listens to changes in that global variable (for example, with an event emitter or an observable), and then every component that consumes it will need to set local state when the global value changes, in order to rerender itself.

context only transmits data to wrapped components, while global variables have no such restriction

While you describe this as a restriction, it's sometimes a very useful benefit.

For example, suppose you are making a group of components that need to work together, such as a TabContainer and a TabPanel. They need to share data between themselves. Since context is only available to the wrapped components, the TabContainer can render a context provider, and the TabPanels can access that context. And if there are multiple TabContainers on the page, they won't interfere with eachother.

Or as another example, suppose you have a Theme object that sets the colors for your app. It's provided via context, and your ui components use it to style themselves. But you also want to let the user change the theme, and see a preview of the change. Since the Theme is using context, you can create a new context provider that just wraps around the preview part of your app. Components inside the preview will use the modified theme, while the rest of the app behaves as normal.

In short: you can put your context provider at whatever level makes sense for your needs. If you want it to be global, put it at the top of your component tree and it's global. But if you want something confined to a region, you can do that too. A global variable does not have this flexibility.

Discussions

reactjs - How to declare a global variable in React? - Stack Overflow
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables ... Sign up to request clarification or add additional context in comments. ... This is honestly a great tip, I was having trouble with my auth tokens since I'm using Server Side Rendering. I ended up loading from localstorage on the first load and then storing it into a separate Config file I can just import. Great answer. 2019-05-02T14:39:31.3Z+00:00 ... You can declare a global ... More on stackoverflow.com
🌐 stackoverflow.com
Is there anything wrong with using global variables?
Use the context API, your implementation isn't guaranteed to stay small. More on reddit.com
🌐 r/reactjs
11
3
May 3, 2019
reactjs - Using context to store variable globally React.js - Stack Overflow
I want to store a global variable that's mutable and accessible in all files of my React.js project, including index.js where the ApolloClient is rendered. At first, I thought to create a class but I More on stackoverflow.com
🌐 stackoverflow.com
Correctly create global variables in React
Global variables are generally a bad idea. I don't know React but perhaps values that need to available throughout your code should be available via a service. ... Save this answer. Show activity on this post. You can do that by storing the variable in window variable · first store the value of your variable in A.js like this ... Sign up to request clarification or add additional context ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
JavaScript in Plain English
javascript.plainenglish.io › react-context-is-a-global-variable-b4b049812028
React Context is a Global Variable | by Fang Jin | JavaScript in Plain English
October 8, 2021 - Quite a few of us argue that a context is local comparing to Redux which is quite global to the site, especially when it comes to where the data is stored. However React context isn’t designed as a local variable, like in the similar sense as in a fiber, or a hook, or anything localized to a unit of work.
🌐
DEV Community
dev.to › chukwuma1976 › information-flow-in-react-the-global-state-of-affairs-with-react-context-31o2
The Global State of Affairs with React Context - DEV Community
June 3, 2023 - A component (User) was created to hold React Context. In this component context (UserContext) and a context provider (UserProvider) were created. Variables were declared and assigned values and subsequently passed as value props. The context provider takes children as props. Our top level component was wrapped with our context provider (UserProvider) which was imported. Hence our child component and subsequent descendants have access to all variables in global context.
🌐
Code Lime
randy-r.github.io › blog › react-context-vs-global-values › index.html
React Context vs global values
September 28, 2019 - One topic I can say I commonly hear when discussing with fellow devs is the justification of using React’s Context for “holding” a value when you can: ... These are all simple and clean (as in obvious) ways to keep global and constant values. By “global” I mean entire-application-global.
🌐
Frontend Undefined
frontendundefined.com › posts › monthly › react-context-global-state
Why React Context is not great for global state
March 6, 2024 - You feed it a value at the top and it magically appears out of all the components subscribed to it. This makes it unsuitable for global state. When you update the value given to the context provider, all components that are subscribed to that ...
🌐
DhiWise
dhiwise.com › post › how-to-use-react-global-variables-a-comprehensive-guide
Enhancing React Applications with Global Variables
June 10, 2024 - This context acts as a global variable that can be accessed and modified by any component that is a consumer of this context. React itself does not have a built-in global state, but it provides the React context API that allows developers to ...
Find elsewhere
🌐
ShareTech
sharetech.in › home › all articles › technology › context api vs global variables in javascript: key differences explained
Context API vs Global Variables in JavaScript: Key... | ShareTech
October 8, 2025 - Learn the key differences between React's Context API and JavaScript global variables. Understand how each stores data, their pros and cons, and when to...
🌐
YouTube
youtube.com › watch
Using React Context For Global State - YouTube
Learn how Level Up uses React Context to manage all global state.
Published   April 23, 2019
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.

🌐
Reddit
reddit.com › r/reactjs › is there anything wrong with using global variables?
r/reactjs on Reddit: Is there anything wrong with using global variables?
May 3, 2019 -

Hey, I'm pretty experienced with programming but somewhat new to React. I'm working on an application which is simple enough in terms of data that integrating Redux would be kind of unnecessary (and would require me to learn how to use the library lol).

There is a very small amount of global data related to the URL, params, and current route/router data that I would like to share with all children of the "app layout" (main content) component. The app layout is the direct child of the router so it has all of the router's info passed to it as props.

I'm thinking about just putting this data in an object on the "window" object from within the constructor of the app layout component, then just accessing it as such from children components. Could this lead to anything bad or is it considered bad practice?

As far as I can tell, my only other option is using the context API. Would that be the better option? Are there any other good options? I'm mostly aiming for simple.

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);
Top answer
1 of 3
5

You can do that by storing the variable in window variable

first store the value of your variable in A.js like this

window.pie = 3.1416;

And you can see the variable value in your Clsb.js component like

console.log(window.pie);
2 of 3
3

As phuzi said in the comment to your question, declaring global variables in react is a bad idea, in this case the ideal would be to use redux, or else the context api (context hook) so you can access and make the variable available throughout your system.

Link to docs https://reactjs.org/docs/context.html

context with functional component

let's create a context like hook

/src/context.js

import React, { createContext, useState, useContext} from "react";

const UserContext = createContext();

export default function UserProvider({ children }) {

//your variables
//example
const [person, setPerson] = useState('John');


    return (
        <UserContext.Provider
            value={{
                person //variables to export
            }}
        >
            {children}
        </UserContext.Provider>
    );
}

export function useUser() {
    const context = useContext(UserContext);
    
    if (!context) throw new Error("useUser must be used within a CountProvider");

    const { person } = context;

    return { person };
}

after creating the context, around your app you need to place the provider

index.js

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

import UserProvider from "./src/context.js";

ReactDOM.render(
    <UserProvider>
        <React.StrictMode>
            <App />
        </React.StrictMode>
    </UserProvider>,
    document.getElementById("root")
);

after you already have the provider you can access any file

src/page.js

import React from "react";
import { useUser } from "./context.js";


const Page = (props) => {

const { getPerson } = useUser(); //variable available by context

return (<h1>Test h1</h1>)
};

export default Page ;

obs: i didn't test the code

🌐
Codelime
codelime.blog › react-context-vs-global-values
codelime.blog - codelime المصادر والمعلومات.
September 28, 2019 - codelime.blog هل هو أول وأفضل مصادر جميع المعلومات التي تبحث عنها. من ضوء الموضوعات العامة إلى مزيد من الموضوعات التي كنت لتتوقعها هنا، codelime.blog تمتلكها جميعًا.
🌐
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 - Context provides a way to share data between components without having to pass explicitly via props. Hooks allow you, among other things, to add state to functional components. Hooks let you use most of React’s features without classes.
🌐
Clerk
clerk.com › blog › understanding-and-properly-using-react-global-state
Understanding and Properly Using React Global State
April 14, 2023 - React Context API vs. Clerk Context Provider ... React global state refers to the data or state that all components in a React application share.
🌐
Stack Overflow
stackoverflow.com › questions › 78493870 › can-i-use-a-global-variable-instead-of-a-react-context-to-pass-constant-props-he
reactjs - Can I use a global variable instead of a React.Context to pass constant props here? - Stack Overflow
I could accidentally invoke ... of question, or is that a way I could go? ... Using a global variable means that your state is stored outside the React components lifecycle....
🌐
Reddit
reddit.com › r/reactjs › is anyone familiar with using context in react to set global variables
r/reactjs on Reddit: Is anyone familiar with using Context in react to set global variables
May 25, 2021 -

We are implementing a user system in our react project using amplify and react context to set the global state of the application to the users information. Since I am relatively new to react and am now taking over this project, I am curious if this is the best practice. When sending an API call, I utilize the "useEffect" hook to grab the users attributes then use it as a parameter for the API call.

We have no senior developer at the moment so some direction would go a long way.

Top answer
1 of 4
2
Storing pervasive, but seldom changing pieces of data within an application is definitely a good use for the Context API. It will allow you to pull this data into any component that needs it (assuming it is a child of the context provider), so I think that this is a good place to start. A few things though: If you're just sort of "setting and forgetting" the user state then I think this would be a good path to continue. You know like, the user logs in, and then you just want to read from that user state over and over again. If you find yourself needing to write back to it or other pieces of 'global' state, I'd recommend taking the time to dive into a state management system like Redux . I'm not really sure if the useEffect hook is your friend here, you'd likely want to read these user values with the useContext hook in whatever component they're necessary. This is more subjective, but I think based off the problem you described: "I have a global user value that I need to attach information from on to requests to my backend" then it would almost make sense to come up with a custom hook that acts as a factory for your fetcher function. Something like, useUserBoundFetch() or something, and it internally calls useContext and returns a function that implements the fetch API standard. That way you can encapsulate all of that into one function, use it interchangeably in your app with a normal fetch implementation, and it can act as the fetcher argument for fetch-helping libraries like SWR . The last bit is just a way to think about solving the problem, I don't know all the ins and outs of your use cases but consider it a jumping off point.
2 of 4
1
I may be late but let me give an answer anyway. There is a hook library that I made and it has a GlobalStateProvider and useGlobalState hook. You can check the docs here . With this, you can access the global state easily in your all components
🌐
4Geeks
4geeks.com › lesson › context-api
Global state with the Context API
June 14, 2025 - Lack of centralized state management: Without a proper structure, updating the state globally can become messy. React provides us with the Context API to share data without manually passing props, and useReducer helps us handle state changes in a predictable and structured way.
🌐
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 - If we use regular global variable to store react global state we won't be able to get the latest value of our state right away when it gets updated, because there's no way for react to know if a global variable has changed for it to re-render ...