loading...

React Hook – Async function in useEffect

iquirino profile image Igor Quirino Originally published at wareboss.com ・1 min read

From: https://wareboss.com/react-hook-async-function-in-useeffect/

If you already know the error message:

"React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing"

Here is a little explanation of why this occurs and how to solve them.

This issues occurs when you directly call a Promise from useEffect Hook.

export default function Example() { 
    const [data, setData] = useState(false)

    useEffect(async () => {
      let response = await fetch('api/data') //Direct call
      response = await res.json()
      setData(response)
    }, []);

  return <div>{data}</div>;
}

The useEffect hook expcect to receive a function to cancel or release resources.

To solve this issue you need to call a Syncronous method. Event if this new one are Async.

export default function Example() { 
    const [data, setData] = useState(false)

    useEffect(() => {
      const runAsync = async () => {
        let response = await fetch('api/data')
        response = await res.json()
        setData(response)
      };
      runAsync();
    }, []);

  return <div>{data}</div>;
}

You can cancel this fetch when the component get destroyed, but this is another article (React Hook – Clean Up useEffect).

Bye!

Posted on by:

iquirino profile

Igor Quirino

@iquirino

I love to help people to solve their problems.

Discussion

markdown guide