reactjsreact-component

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


Solution

  • 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)