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.

Answer from phry on Stack Overflow
🌐
React
legacy.reactjs.org › docs › context.html
Context – React
The propagation from Provider to its descendant consumers (including .contextType and useContext) is not subject to the shouldComponentUpdate method, so the consumer is updated even when an ancestor component skips an update. Changes are determined by comparing the new and old values using the same algorithm as Object.is. ... The way changes are determined can cause some issues when passing objects as value: see Caveats. class MyClass extends React.Component { componentDidMount() { let value = this.context; /* perform a side-effect at mount using the value of MyContext */ } componentDidUpdate() { let value = this.context; /* ...
🌐
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.
Discussions

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 wasn't sure how to implement that and save the state of the variable across multiple pages. Upon doing research, I discovered the use of context... More on stackoverflow.com
🌐 stackoverflow.com
When Should i use use context and when should i use global state managment . I am new to react can you share some best pratices.
tldr; Use global state management libraries for global state management. Keep context for passing props. Context is about passing props. We can achieve a "global state management" experience by passing state and setState in those props. One big con to using context with global state is that any component that pulls in context will re-render when any piece of global state updates. Example. You have a context that contains the variables buttonColor , textColor, and username . You have two custom components which pulls in textColor and which pulls in buttonColor , both from context. For some reason, you make an update to the username variable in context. Even though it's not used in or component, it will force re-renders on them because they depend on the context state in general. This is where zustand or any global state management differs. They allow you to pull from global state and will only re-render the component when those you selected change. More on reddit.com
🌐 r/reactjs
33
31
March 26, 2023
reactjs - How manage global state using context API in React js - Stack Overflow
I am having issues managing the state of my navbar using useContext. Atm my app renders the menu items as soon as the menu toggle. I want this event to happen only onClick, also the button does not... More on stackoverflow.com
🌐 stackoverflow.com
Is anyone familiar with using Context in react to set global variables
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. More on reddit.com
🌐 r/reactjs
6
2
May 25, 2021
🌐
Medium
medium.com › @QA-initi › how-to-create-global-context-in-react-f02c9d91270b
How to create Global Context in React | by QA-init | Medium
August 28, 2025 - Step 3: Consume the Context Any component that wants to access the global data can consume the context using the useContext hook or by wrapping the component with Consumer. ... import React, { useContext } from 'react'; import GlobalContext ...
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);
🌐
Clerk
clerk.com › blog › understanding-and-properly-using-react-global-state
Understanding and Properly Using React Global State
April 14, 2023 - This article starts by explaining the benefits of using global state in React and when it's best to use it. It then shows you how to implement global state in React using two methods: a custom implementation of a React context using the context API⁠ and an implementation of the Clerk React context API component.
🌐
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 - Our state variable user and setter ... variables in global context. A fetch request is performed and if there is a user logged in then user will be set to that value, otherwise user will remain null....
Find elsewhere
🌐
YouTube
youtube.com › coding addict
React 18 Tutorial - Global Context - YouTube
React 18 Tutorial Episode 102 - Global ContextWeb Dev Courses - https://www.johnsmilga.com/Entire Playlisthttps://www.youtube.com/watch?v=GcrNHMcL-WM&list=PL...
Published   February 12, 2023
Views   3K
🌐
Endertech
endertech.com › articles › using react’s context api for global state management
The React Context API for Global State Management | Endertech
November 17, 2023 - In a newly created React project, you will want to create two folders within the src directory: components & context. Move into the context directory and create two files: GlobalState.js & AppReducer.js
🌐
Medium
medium.com › @codenova › how-to-use-react-context-api-for-global-state-management-612bb40ecca9
How to use React Context API for global state management? | by Codenova | Medium
October 17, 2024 - Finally, we will cover some best practices for using the React Context API. Let’s get started! In React, global context refers to a mechanism for passing data down the component tree without relying on props.
🌐
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 - If you’re reading this article, you probably are familiar with the following React vocabulary, but in case you need a refresher: 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. We’ll store our global state and the functions to update them in a Context object and we’ll use Hooks to update the global settings stored within that object.
🌐
4Geeks
4geeks.com › lesson › context-api
Global state with the Context API
June 14, 2025 - To allow all components to access the global state, we need to wrap our application with the StoreProvider in the main file. 1import React from "react"; 2import ReactDOM from "react-dom"; 3import { StoreProvider } from "./context/StoreContext"; ...
🌐
Plasmic
docs.plasmic.app › learn › global-contexts
Global Contexts | Learn Plasmic
Provide data via React Contexts to consumers in code components · Provide data to Studio pages and components via DataProvider · Provide actions to Studio pages and components via GlobalActionsProvider · A global context is like any other React Component. For example, here’s a global context that implements authentication, providing the current user ...
🌐
GitHub
github.com › eleme › react-context-global-store
GitHub - eleme/react-context-global-store: A simple global store based on React context · GitHub
Then use the connect method to connect your component to the store: // app.js import React from 'react'; import { connect } from 'react-context-global-store'; class App extends React.Component { } export default connect(App, ['counter']); Finally use this.props.store inside the component to get the defined context and update your context with setStore Tips: Just like setState, you can pass in a callback function to get the updated context
Starred by 22 users
Forked by 2 users
Languages   TypeScript 95.9% | JavaScript 4.1%
🌐
Scientyfic World
scientyficworld.org › home › blog archive › web dev › react › how to use react context api for global state management?
How To Use React Context API For Global State Management? | Scientyfic World
April 30, 2023 - With the Context API, you can create a context object and share it with any component that needs it. In React, global context refers to a mechanism for passing data down the component tree without relying on props.
🌐
Medium
atulfind.medium.com › react-global-state-management-using-context-and-reducer-fa5b85f43b61
React: Global state management using context API and reducer.
November 9, 2023 - B: To access global data we need to use useContext and pass globalContext in hooks argument. ... So far we have done the required implementation, but if you see globalData variable in the App component it does not return anything, it is just ...
Top answer
1 of 2
1

You can try out this implemetation with reducers to handle for you the state change with localstorage. It is not an exact implemetation of your's but you can see the flow

In the AppContext.jsx

The AppContext holds the global state of the application so that it's easier working with a single context provider and dispatching actons to specific reducers to handle state change without providing many providers. The combinedReducers handle reducer methods to a given state component

import { useReducer, createContext, useEffect } from "react";
import userReducer from "./reducers/userReducer";
import themeReducer from "./reducers/themeReducer";
export const APP_NAME = "test_app";

//Check the localstorage or set a default state
const initialState = JSON.parse(localStorage.getItem(APP_NAME))
  ? JSON.parse(localStorage.getItem(APP_NAME))
  : {
      user: {
        username: "",
        email: "",
        isAdmin: false,
      },
      theme: { dark: false },
    };
//Create your global context
const AppContext = createContext(initialState);

//Create combined reducers
const combinedReducers = ({ user, theme }, action) => ({
  user: userReducer(user, action),
  theme: themeReducer(theme, action),
});
const AppState = ({ children }) => {
  //Making it to provider state
  const [state, dispatch] = useReducer(combinedReducers, initialState);
  useEffect(() => {
    localStorage.setItem(APP_NAME, JSON.stringify(state));
  }, [state]);
  return (
    <AppContext.Provider value={{ state, dispatch }}>
      {children}
    </AppContext.Provider>
  );
};

export default AppState;

export { AppContext, AppState };

The above implementation works like redux but you destructure the given state to a specific reducer to handle the state change

In this I have used localstorage to keep a persistent state because with context API on page reload the state goes. Use the useEffect hook from react and add the state in the dependency array to ensure your state is in sync

In the UserReducer.jsx

const userReducer = (state, action) => {
  const { type, payload } = action;
  switch (type) {
    case "LOGIN":
      return { ...state, ...payload };
    case "LOGOUT":
      return {};
    default:
      return state;
  }
};

export default userReducer;

In the ThemeReducer.jsx

const themeReducer = (state, action) => {
  const { type, payload } = action;
  switch (type) {
    case "DARK":
      return { ...payload };
    default:
      return state;
  }
};

export default themeReducer;

Wrapping the whole app with a single provider in the index.jsx

import reactDom from "react-dom"
import React from "react"
import App from "./App"
import "./index.css"
import AppState from "./state/AppState"

reactDom.render(
    <React.StrictMode>
        <AppState >
            <App />
        </AppState>
    </React.StrictMode>,
    document.getElementById("root")
)

Accessing the context from App.jsx

import { useContext } from "react";
import { AppContext } from "./state/AppState";
const App = () => {
  const { state, dispatch } = useContext(AppContext);
  const handleLogin = () => {
    dispatch({
      type: "LOGIN",
      payload: {
        username: "Mike",
        email: "[email protected]",
        isAdmin: false,
      },
    });
  };

  const handleLogout = () => {
    dispatch({
      type: "LOGOUT",
      payload: {},
    });
  };

  return (
    <div className="main-container">
      <div className="container">
        <p>Username: {state.user.username ? state.user.username : "Unknown"}</p>
        <p>Email: {state.user.email ? state.user.email : "Unknown"}</p>
      </div>
      <button onClick={handleLogin}>Login</button>
      <button onClick={handleLogout} style={{ background: "red" }}>
        Login
      </button>
    </div>
  );
};

export default App;

Here is my code LINK if you want to see the structure Github

2 of 2
0

Short answer, use react-context-slices. It's a library that allows you to define slices of Context and fetch them through a unique hook, useSlice. You must pass the name of the slice you want to fetch and this hook will return to you the value or state of the slice and a setter/dispatch function, depending on if you defined a reducer or not for the slice.

Here is an example on how you do it with this library:

// slices.js
import getHookAndProviderFromSlices from "react-context-slices"
export const {useSlice, Provider} = getHookAndProviderFromSlices({
  count: {initialArg: 0},
  // rest of slices of Context you want to define
})
// app.js
import {useSlice} from "./slices"
const App = () => {
  const [count, useCount] = useSlice("count")
  return <>
    <button onClick={() => setCount(c => c + 1)}>+</button>{count}
  </>
}

Hope this helps anyone planning to use Context API for state management in a react app.

🌐
Medium
medium.com › @samuelresua › global-state-with-react-context-cfa99946900d
Global State with React Context. A neat optimised pattern for reduxless… | by Samuel Resua | Medium
December 9, 2021 - Next we need to consume our state, Reacts useContext hook makes this very straight forward · Again, to reiterate separating our dispatch and state contexts is an optimisation that will stop components who are only interested in triggering updates from re-rendering when our state changes. We have implemented an optimised reduxless global ...
🌐
CodeBurst
codeburst.io › global-state-with-react-hooks-and-context-api-87019cc4f2cf
Global state using only React Hooks with the Context API (No Redux) | by Amir Off | codeburst
April 21, 2022 - How to create a global app state without Redux using React’s latest built-in features: React Hooks and the Context API
🌐
GitHub
github.com › kqito › use-global-context
GitHub - kqito/use-global-context: A new way to use “useContext” better with selector
API to merge specific initial states for props passed to createGlobalContext. This API is useful for inheriting the value of the store from the SSR in the browser. ... Specifies the value of the base context. source (type: PartialState<GlobalContextReducers> | undefined)
Author   kqito