The problem is that countryname ( separate from countryName) is scoped only to your function getData. Variables in JavaScript are scoped to the function/block they are defined within, depending on how you declare them (var vs let/const). In this case, countryName is available everywhere within your component, while countryname is only available within getData. This is a JavaScript-ism, and has nothing to do with you using React.

Answer from rfestag on Stack Overflow
🌐
W3Schools
w3schools.com › react › react_es6_variables.asp
React ES6 Variables
Unless you were in strict mode, ... ways of defining your variables: var, let, and const. ... If you use var outside of a function, it belongs to the global scope....
Discussions

React variables scope, defined how?
This is mostly a security question, How does React store all it's javascript variables/state? Is there any way from the window object, to access a variable defined inside react? Lets say you ar... More on github.com
🌐 github.com
1
June 30, 2017
reactjs - React when to use global variables instead of states - Stack Overflow
State is like the core of React, there's really no reason to avoid using it. 2021-04-13T18:35:39.667Z+00:00 ... The negative part of using variable outside component is you are essentially setting it as a global window variable, meaning if you have any scripts using the same global variable then you gonna end up with bugs. 2021-04-13T18:36:40.227Z+00:00 ... isn't the variable scope ... More on stackoverflow.com
🌐 stackoverflow.com
React JS Access variable outside of scope - javascript
I'm trying to format numbers using numeral js - this is working I log number. How can I access the let number whilst it's outside of the render function to pass down to the element "unit-item-num... More on stackoverflow.com
🌐 stackoverflow.com
February 22, 2017
Reactjs - accessing variables - Stack Overflow
How can I access variable bvar in the code below? Also, when would I declare variables as: a) state b) between constructor() and render() c) inside render() - my understanding is that I'd set them More on stackoverflow.com
🌐 stackoverflow.com
🌐
Medium
medium.com › @jonatanramhoj › react-scopes-demystified-6e5d1a40a7c2
React: scopes demystified. Understanding the different contexts in… | by Jonatan Ramhöj | Medium
June 1, 2023 - In React, there’s only module scope and component scope. Variables declared in files like app.js or index.js are also within module scope, rather than being automatically accessible throughout the app.
🌐
Altcademy
altcademy.com › blog › how-to-use-variables-in-reactjs
How to use variables in ReactJS - Altcademy.com
November 8, 2023 - In this example, we use the curly ... in ReactJS to describe what the UI should look like. In programming, scope refers to where a variable can be used....
🌐
Medium
medium.com › the-andela-way › fundamental-javascript-concepts-to-help-you-get-started-with-react-7067763d3697
Fundamental Javascript Concepts to help you get started with React | by Cecilia Wahome | The Andela Way | Medium
April 27, 2018 - They can be stored in variables, ... to the MDN Docs, Scope is the current context of execution; the context in which values and expressions are “visible,” or can be referenced....
🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › tech guides & tutorials
How to Use Variables within Classes | Pluralsight
March 19, 2020 - In the above example, there is one static variable called num1 whose value is fixed. This means no one can change its value into the current component, but they can use it for the rendering purpose. In the same way, the state object can also be used as a static value. import React, { Component } from "react"; import { render } from "react-dom"; class App extends Component { state = { name: 'Hello World', age: '30' }; render() { const { name, age } = this.state; console.log(this.state) return ( <div> </div> ); } } render(<App />, document.getElementById("root"));
🌐
StackBlitz
stackblitz.com › edit › react-variable-scope
React Variable Scope - StackBlitz
Starter project for React apps that exports to the create-react-app CLI.
🌐
GitHub
github.com › facebook › react › issues › 10080
React variables scope, defined how? · Issue #10080 · facebook/react
June 30, 2017 - This is mostly a security question, How does React store all it's javascript variables/state? Is there any way from the window object, to access a variable defined inside react? Lets say you are also using redux, and you store some sensi...
Author   cristianocca
Find elsewhere
🌐
Atomic Spin
spin.atomicobject.com › 2020 › 04 › 08 › react-contexts-dynamic-scope
React Contexts are Dynamic Scope - Atomic Spin
June 16, 2022 - To bind a new value to the variable, you render the Provider component. That new value will apply to any component that is rendered within that Provider — unless another <Name.Provider> is rendered inside it at some point. Then whatever value is supplied will apply to components rendered within only the innermost Provider. There is one difference: React Contexts are scoped to the components, not the call stack.
🌐
React
legacy.reactjs.org › docs › jsx-in-depth.html
JSX In Depth – React
Capitalized types indicate that the JSX tag is referring to a React component. These tags get compiled into a direct reference to the named variable, so if you use the JSX <Foo /> expression, Foo must be in scope.
🌐
Klocwork
help.klocwork.com › 2024.1 › en-us › reference › js.react.react.in.jsx.scope.htm
JS.REACT.REACT.IN.JSX.SCOPE | Klocwork 2024.1
When using JSX, <a /> expands to React.createElement("a"). Therefore the React variable must be in scope.
🌐
About React
aboutreact.com › home › react native global scope variables | initialize once use everywhere
React Native Global Scope Variables | Initialize once use Everywhere
December 10, 2022 - They can be used on any screen as local variables but the difference is their scope is global. In React Native we can make any variable Global Scope Variables by just putting global as prefix.
🌐
W3Schools
w3schools.com › js › js_scope.asp
JavaScript Scope
Each JavaScript function have their own scope. Variables defined inside a function are not accessible (visible) from outside the function.
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

🌐
DhiWise
dhiwise.com › post › how-to-use-react-global-variables-a-comprehensive-guide
Enhancing React Applications with Global Variables
June 10, 2024 - To optimize performance, react developers should minimize the number of times components re-render due to changes in the global state. This can be achieved by using React hooks like useMemo and useCallback. Environment variables are often used for storing configuration settings and sensitive information.
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Really struggling with react - JavaScript
November 29, 2022 - So, I’m really struggling with React… It’s just a lot different than regular JavaScript. I’m just messing around and trying to get comfortable with what I’ve learned before moving on and the structure of things in React just really throw me off. My question is how come I don’t have access to the variable total outside of my sumOfTwo function?
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.

🌐
CodeBurst
codeburst.io › react-state-vs-props-explained-51beebd73b21
React State vs Props explained. Compare React components to plain… | by Manoj Singh Negi | codeburst
September 10, 2018 - class DummyComponent extends React.Component { state = { name: 'Manoj' } render() { return <div>Hello {this.state.name}</div>; } }const DummyFunction = () => { let name = 'Manoj'; console.log(`Hey ${name}`) } As you can see a component state can be compared to a function local scope. We defined a name property inside Component state and used it inside the render process. Similarly inside the function we defined a variable name and used it inside the function.