Use Async in React Scenarios

in Technology, React Sitevisits: -- Pageviews: --

In a typical software architect that seperates backend (Nodejs) and frontend (React), the frontend is quite ‘light weighted’ in terms of operations regarding data (Also grâce à the tools like react-redux, the frontend development is easier). That means we normally do not need to cope with scenarios that needs to write complex Nodejs code on the frontend side as it is just a viewer. However, due to certain features of React, there are some scenarios that we need to pay attention to. In this article, I summarise two typical scenarios that using ‘async’ within React in a recent project.

Calling Async Method in ‘useEffect’

There are some cases that we need to call async method in useEffct. Can we do things like below:

1
2
3
4
5
useEffect(async () => {
...
await axios.post(...)
...
}, [])

No, we cannot. Why? Because the async axios call returns promise and the useEffect does not expect callback function to return promise. The useEffect waits for the return of nothing or a function.

Then what we should do? There are two methods

  • Define an async function inside useEffect
1
2
3
4
5
6
7
useEffect(() => {
...
async () => {
await axios.post(...)
}()
...
}, [])
  • Define an async function outside useEffect
1
2
3
4
5
6
7
8
9
10
const getData = useCallBack (async () => {
...
await axios.post(...)
...
}, [])

useEffect(() => {
getData()
}, [getData])

Use Async in ‘setInterval’

1
2
3
setInterval(async () => {
await axios(...)
}, 1000)

Can we do things like above in setInterval? It is questionable, as the async call may cost more than the time set in setInterval method. So what is the better option? Use Promise with setTimeout, like below:

1
2
3
4
5
6
7
8
9
10
11
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}

async function loop() {
while (/* condition */) {
/* code to wait on goes here (sync or async) */

await delay(100)
}
}

Reference: https://stackoverflow.com/questions/51830200/how-to-await-inside-setinterval-in-js

The above are the two scenarios that I met in my project, when I look back as a new full-stack engineer (I was heavily involved in backend dev, not frontend):)

Comment and share

  • page 1 of 1
Author's picture

Jingjie Jiang


Find a place I love the most