avatar

Hassan khan

Last updated: November 07,2022

Async react useEffect

Async react useEffect


You cannot make async the original function of useeffect directly but there are other ways to achieve the async feature.


There are two basic ways to make useEffect async.

1) Create IIFE function in useEffect.

2) Create an async function in useEffect and call it in useEffect.


1) useEffect with IIFE function example:

1
2
3
4
5
  useEffect(() => {
    (async () => {
      //perform your task here
    })();
  }, []);

2) useEffect with async function example:

1
2
3
4
5
6
7
8
useEffect(() => {
    const MyFunction = async () => {
      //perform your task here
    };

    //Call it here
    MyFunction();
  }, []);

You can achieve async functionality in useEffect with the help of the above examples.


Share