Skip to content

Commit 299256e

Browse files
committed
➕ how-to-use-async-function-in-useEffect-hook.md
1 parent 6b9b54b commit 299256e

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
---
2+
slug: how-to-use-async-function-in-useEffect-hook
3+
title: How to use async function in useEffect hook?
4+
author: Bunlong
5+
author_title: React Patterns Team
6+
author_url: https://github.com/Bunlong
7+
author_image_url: https://avatars1.githubusercontent.com/u/37023003?s=400&u=0049c6773040efb265cdf622076305f8b47facec&v=4
8+
tags: [hook]
9+
image: /img/how-to-use-async-function-in-useEffect-hook.png
10+
---
11+
12+
![How to use async function in useEffect hook?](/img/how-to-use-async-function-in-useEffect-hook.png "How to use async function in useEffect hook?")
13+
14+
## How to use async function in useEffect hook?
15+
16+
At first glance you will have an idea as following.
17+
18+
```jsx
19+
useEffect(async () => {
20+
await someTask();
21+
}, []);
22+
```
23+
24+
**What's wrong?**
25+
26+
The compiler should be yielding something as following.
27+
28+
```
29+
Argument of type '() => Promise<void>' is not assignable to parameter of type 'EffectCallback'.
30+
```
31+
32+
<!--truncate-->
33+
34+
Do you start seeing the problem here? Let's take a look the [useEffect hook](https://reactjs.org/docs/hooks-reference.html#useeffect) to get more informations.
35+
36+
The problem is `useEffect` expects a clean-up function in return to clear the created resources before the component leaves the screen, but when we use async function it return a promise instead.
37+
38+
## How to deal with async function in useEffect hook?
39+
40+
You can define an async function inside `useEffect` and then call it over there as following.
41+
42+
```jsx
43+
useEffect(() => {
44+
// Create an scoped async function in the hook
45+
async anyNameFunction() => {
46+
await someTask();
47+
}
48+
49+
// Execute the created function directly
50+
anyNameFunction();
51+
}, []);
52+
```
53+
54+
You can also us an IIFE (Immediately Invoked Function Expression) as following.
55+
56+
```jsx
57+
useEffect(() => {
58+
(async anyNameFunction() => {
59+
await someTask();
60+
})();
61+
}, []);
62+
```
66.5 KB
Loading

0 commit comments

Comments
 (0)