Skip to content
Advertisement

React state resets when calling an async function

I’m trying to display a loader in react then execute an async function and then removing the loader but seems like the loader disappears as soon as the function starts executing.

Here’s a sample code:

const component = () => {
    const [showLoader, setShowLoader] = useState(false)
    
    const clickHandler = async (status: string) => {
        setShowLoader(true)
        const success = await someAsyncFunction()
        success ? setShowLoader(false) : true
    }

    return (<div hidden={!showLoader}><Loader /></div>)
}

[Edit] Here is a simplified version of my someAsyncFunction:

const someAsyncFunction = async() => {
    for (let i=0;i < 99999;i++){
        console.log(i)
    }
    return Promise.Resolve(true)
}

It is evident that someAsyncFunction does return resolve the Promise and no sooner as it executes the loop for about 100K times

Advertisement

Answer

Given the nature of useState hook, it doesn’t set the value instantly instead it’s sort of a request queue. In this case, before the state is update, the function is called.

Best approach would be to use an useffect hook with the showLoader as it’s dependency, and execute the function within it as it ensures the execution only after the state is set

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement