Sobes.tech
Junior — Middle

How to implement asynchronous operations inside the useEffect hook in React?

sobes.tech AI

Answer from AI

In React, inside the useEffect hook, you cannot directly make the function asynchronous (you cannot write async before the function passed to useEffect), because useEffect expects either a cleanup function or nothing.

The correct way is to declare an asynchronous function inside the effect and call it:

useEffect(() => {
  async function fetchData() {
    const response = await fetch('/api/data');
    const data = await response.json();
    // update state or perform other actions
  }
  fetchData();
}, []);

Or use an arrow function:

useEffect(() => {
  const fetchData = async () => {
    const response = await fetch('/api/data');
    const data = await response.json();
    // update state
  };
  fetchData();
}, []);

This approach allows performing asynchronous operations inside useEffect correctly.