Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React when to use global variables instead of states

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.

Would it be an antipattern if I keep using this method to put passive data to be memorized throughout renders?

var cityList;
function Component(){
    
    useEffects(async ()=>{
        if (!cityList)}{
            cityList = await loadCities();
        }
    });
    
    ...
}

Additionaly I know I can use hooks like useMemo(). But I want to know if this has a problem.

Most importantly, What is a possible reason to use variables like this instead of State or memo

like image 690
Abraham Avatar asked Oct 19 '25 15:10

Abraham


2 Answers

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)

like image 112
Someone Special Avatar answered Oct 21 '25 06:10

Someone Special


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

like image 31
the_previ Avatar answered Oct 21 '25 07:10

the_previ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!