Handling Asynch Functions in React
Sometimes you'll need to call an asynchronous function in order to fetch some data or dynamically import a module. In those instances, wrap the asynchronous function call inside of a useEffect hook.
const [data, setData] = useState()
useEffect(() => {
const loadData = async () => {
const data = await fetchData()
setData(data)
}
loadData()
})
The magic here happens when we call the asynchronous function loadData()
but without await
. This calls the function but does not wait for it to complete, allowing React to continue rendering, and preventing the main thread from being blocked while waiting for `loadData()` to resolve.