How to apply useEffect on async await

How to apply useEffect on async await

Let's consider a real-time example of using useEffect for fetching data from an API.

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

function DataFetchingExample() {
  // State variables
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // useEffect for data fetching
  useEffect(() => {
    // Function to fetch data from an API
    const fetchData = async () => {
      try {
        const response = await fetch('');
        const result = await response.json();
      } catch (error) {
      } finally {

    // Call the fetchData function
  }, []); // Empty dependency array means this effect runs once after the initial render

  // Render based on data fetching status
  if (loading) {
    return <p>Loading...</p>;

  if (error) {
    return <p>Error: {error.message}</p>;

  return (
      <h1>Data from API</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>

export default DataFetchingExample;

In this example:

  • We have a component DataFetchingExample that fetches data from an API using the fetch function inside the useEffect.

  • The loading, error, and data states are used to manage the different states of the data fetching process.

  • The component initially renders a loading message while the data is being fetched. If an error occurs, it displays an error message. If the data is successfully fetched, it displays the data.


This is a simplified example, but it illustrates how useEffect can be used to manage the asynchronous nature of data fetching in React components. The effect runs once after the initial render, fetches data, and updates the component's state accordingly.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!