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.

🌐
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 - Now, any child component of the AppContext.Provider wrapper has access to both global variables and the functions to update them: // components/MyComponent.js import { useContext } from 'react'; import AppContext from './AppContext'; export ...
Discussions

Best way to initialise a global variable?
More context is required here. Could be something that can go in the .env More on reddit.com
🌐 r/reactjs
12
1
December 6, 2023
Storing non-state variables in functional components
Below are two React Components that do almost the same thing. One is a function; the other is a class. Each Component has an Animated.Value with an async listener that updates _foo on change. I need to be able to access _foo in the functional component like I do with this._foo in the classical component. FunctionalBar should not have _foo in the global ... More on stackoverflow.com
🌐 stackoverflow.com
How to access a Global variable in React JS functional component?
I have a global variable in the window object in a functional React component. It's Global --> Designer --> nodes --> NODE_FORM --> props --> dataSource deep. How can I access it in... More on stackoverflow.com
🌐 stackoverflow.com
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't see the purpose since nothing in my code reacts to change to the data. More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 1
2

Functional components are executed from top to bottom whenever state changes, so the whole function is re-executed and that's how it returns the new JSX, compare this to class components where only render() function is executed on render, that's how functional components work.

The problem is that your global variables are in fact not global and a part of the function, hence they are re-initialized each time render is happening.

Two ways to solve this

Move your variables to the state

function Stopwatch() {
  const [timeState, setTimeState] = useState({
    status: false,
    ms: 0,
    seconds: 0,
    minutes: 0,
    stopms : null,
    stopSeconds : null,
    stopMinutes: null,
  });

  const handleClick = () => {
    changeStatus();
    if (timeState.status) {
      clearInterval(timeState.stopms);
      clearInterval(timeState.stopSeconds);
      clearInterval(timeState.stopMinutes);
    } else {
      let stopms = setInterval(changeMs, 1);
      let stopSeconds = setInterval(changeSeconds, 1000);
      let stopMinutes = setInterval(changeMinutes, 60000);

      setTimeState(prev => ({..prev, stopms, stopSeconds, stopMinutes})); // update the values in state
    }
  };

   ...... 

   const handleReset = () => {
    clearInterval(timeState.stopms); // use the same values to clear them
    clearInterval(timeState.stopSeconds);
    clearInterval(timeState.stopMinutes);
    .....
  };

 ..... 

 } 

Or make them global by placing them outside of your component, Will work but not recommended.

In your component file.

 // declare them just above your function
 let stopms;
 let stopSeconds;
 let stopMinutes;
  
 function Stopwatch() {
  const [timeState, setTimeState] = useState({
    status: false,
    ms: 0,
    seconds: 0,
    minutes: 0,
  });
  .....

  const handleClick = () => {
    changeStatus();
    if (timeState.status) {
      clearInterval(stopms);
      clearInterval(stopSeconds);
      clearInterval(stopMinutes);
    } else {
      stopms = setInterval(changeMs, 1);
      stopSeconds = setInterval(changeSeconds, 1000);
      stopMinutes = setInterval(changeMinutes, 60000);
    }
   .......
  };
    
    
🌐
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?

🌐
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 - When a global state receives update request, it performs the update and notify all components subscribed to it for them to update themselves(re-render) Here is the architectural diagram for more clarification · You are probably already familiar with this design pattern, it's quite popular, it's called Observer Design Pattern. With this and a little help from hooks, we'll be able to manage global state completely with global variables. ... function GlobalState(initialValue) { this.value = initialValue; // Actual value of a global state this.subscribers = []; // List of subscribers this.getValu
🌐
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 on the web page, including the script for the React app. Since window is a global object, the React code can also access its properties, as shown below. import React from "react"; class App extends React.Component { constructor(props) { super(props); this.state = { user: window.user, }; } render() { const { user } = this.state; return ( <div> <p> ID: {user.id} </p> <p> Name: {user.name} </p> </div> ); } }
Find elsewhere
🌐
DhiWise
dhiwise.com › post › how-to-use-react-global-variables-a-comprehensive-guide
Enhancing React Applications with Global Variables
June 10, 2024 - Additionally, state management libraries like Redux can be used to manage global state in React applications. In JavaScript, you can declare a variable global by defining it outside of any function or class, ...
🌐
sebhastian
sebhastian.com › react-global-variable
Declare React global variable with code examples | sebhastian
July 7, 2022 - It will be accessible from all the components you have in your application. First, create a file named .env in your root directory: ... Then declare a global variable in the env file. The convention in .env file is to use all uppercase letters for the variable name: ... export default function App() { return ( <div className="App"> <h1>Hello {process.env.REACT_APP_NAME_VARIABLE}</h1> <h2>Start editing to see some magic happen!</h2> </div> ); }
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

🌐
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.
🌐
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;
🌐
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 - In both concepts the purpose of global(state & variable) is to allow sharing of a value among entities which might be functions, classes, modules, components etc, while the purpose of local(state & variable) is to restrict its usage to the scope ...
🌐
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.
🌐
Reddit
reddit.com › r/reactjs › are props like global variables?
r/reactjs on Reddit: Are props like global variables?
March 26, 2022 -

Sorry if you're being bombarded with newbie questions everyday, but I'm confused af.

Are props objects that represent the components' data?

Why use props instead of global variables?

Been reading around but can't find a post that makes me understand fully.

Also, just noticed this but, shouldn't this sub's description say "React by Meta" instead of "React by Facebook"?

🌐
Reddit
reddit.com › r/reactjs › is usestate a must or can we do our work by using a global variable in a component?
r/reactjs on Reddit: Is useState a must or can we do our work by using a global variable in a component?
February 25, 2024 -

Hello!

I have implemented a search functionality in which I am inputting a search text and in an input field and then searching for the same in the chat window. I am also keeping track of total number of search result using a variable named count;

Earlier I used useState to set/update the count but I found that whenever it used to update the state of count , it was re rendering the entire component making other values to initial ones, which caused problems.

So, in react.js , can we use a global variable eg: count for keeping track of search result or is it the case that we must use useState to increment/keep track of the current count value?

🌐
Medium
rajeshnaroth.medium.com › component-state-management-in-react-functional-components-with-hooks-e7c412c05e71
Component State Management in React Functional Components with hooks
June 25, 2020 - With co-location, a feature’s state is kept close to its functionality as much as possible, it is sometimes organized with in a single folder. Each feature should manage only its own data. Any required global state should be injected into the feature “container”. A container is a React Component ...
🌐
Delft Stack
delftstack.com › home › howto › react › global variable in react
Global Variable in React | Delft Stack
January 27, 2022 - So, let’s import this file in App.js and use the global variable. # react import "./styles.css"; import globeVar from "./GlobalVar"; export default function App() { return ( <div className="App"> <h2>{globeVar}</h2> </div> ); }
🌐
GitHub
github.com › donnikitos › react-useGlobal
GitHub - donnikitos/react-useGlobal: A React.js hook to share and use global variables between unconnected components. · GitHub
If the global variable is alrady set and has a value, the second argument (initial value) will be ignored. The hook returns a tuple of a getter variable and a setter function very much like a normal useState hook in React.js. 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] = use
Author   donnikitos