📜  async useEffect - Javascript (1)

📅  最后修改于: 2023-12-03 15:29:31.509000             🧑  作者: Mango

Async useEffect in Javascript

React Hooks introduced several new features to simplify state management and lifecycle methods in functional components. Among these, the useEffect hook allows you to perform side effects in a function component. However, useEffect is not suitable for asynchronous operations out of the box.

async useEffect is a technique to perform asynchronous operations inside a useEffect hook. It involves wrapping the hook in an anonymous async function and using await for asynchronous operations. Here is an example:

import React, { useState, useEffect } 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();
  }, []);

  if (!data) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.completed ? 'Complete' : 'Incomplete'}</p>
    </div>
  );
}

In this example, we use the useState hook to initialize the data state to null. Then, in the useEffect hook, we define an anonymous async function fetchData to fetch data from an API using fetch and store it in state.

Since useEffect does not support returning a promise, we use an IIFE (Immediately Invoked Function Expression) to initiate the async function and call it right away. The empty dependency array [] ensures that the hook only runs once when the component mounts.

If data is null (i.e. while the API call is in progress), the component will render a "Loading..." message. Otherwise, it will display the title and completed status of the fetched data.

async useEffect is a handy technique to perform asynchronous operations in functional components. It simplifies the code compared to using class components and lifecycle methods. However, it also comes with some pitfalls, such as handling unmounted components and avoiding infinite loops.