react useeffect async

Understanding React useEffect with Async Operations

React useEffect is a hook that allows us to perform side effects in functional components. It is similar to componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods in class components. However, useEffect is more flexible and allows us to manage state and props changes in a clean way.

Async Operations in useEffect

When dealing with async operations inside useEffect, there are a couple of things to keep in mind:

  • The async code should be wrapped inside a function.
  • The function should return a cleanup function if needed.

Here's an example:


  import React, { useEffect, useState } from 'react';

  function App() {
    const [data, setData] = useState(null);

    useEffect(() => {
      async function fetchData() {
        const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
        const json = await response.json();
        setData(json);
      }

      fetchData();

      // cleanup function
      return () => setData(null);
    }, []);

    return (
      <div>
        {data ? <p>{JSON.stringify(data)}</p> : <p>Loading...</p>}
      </div>
    );
  }

In this example, we are fetching data from an API using the fetch function. We are using async/await syntax to make the code more readable. The async function is called inside useEffect, which runs only once (thanks to an empty array as the second argument). When the promise resolves, the state is updated using the setData function. If an error occurs, we can catch it using a try/catch block.

We are also returning a cleanup function that sets state to null. This is useful if we want to cancel an async operation or avoid memory leaks.

Other Ways to Use Async Operations in useEffect

There are other ways to use async operations inside useEffect. For example, we can use a then callback instead of async/await:


  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => setData(json))
      .catch(error => console.error(error));

    return () => setData(null);
  }, []);

We can also define the async function outside useEffect and call it inside:


  async function fetchData() {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    const json = await response.json();
    setData(json);
  }

  useEffect(() => {
    fetchData();

    return () => setData(null);
  }, []);

The choice depends on personal preference and project requirements. However, it's important to remember to clean up after ourselves and to handle errors gracefully.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe