REACT Tutorial



ASYNCHRONOUS REACT


Asynchronous in React

React is designed to build dynamic user interfaces, and often, it needs to interact with servers to fetch or submit data. These operations are asynchronous, meaning they happen in the background and don’t block the UI.

What is Asynchronous?

In simple terms, asynchronous means β€œnot happening at the same time.” In JavaScript (and React), it allows the browser to continue rendering UI while waiting for something to finish β€” like fetching data from an API.

Why Use Asynchronous Code in React?

  • To fetch data from APIs.
  • To send form data to a server.
  • To handle delays without freezing the UI.
  • To load components or resources dynamically.

Example: Using async/await in useEffect()

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

function Quote() {
  const [quote, setQuote] = useState('');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchQuote() {
      try {
        const response = await fetch('https://api.quotable.io/random');
        const data = await response.json();
        setQuote(data.content);
      } catch (err) {
        setQuote('Failed to load quote.');
      } finally {
        setLoading(false);
      }
    }
    fetchQuote();
  }, []);

  return (
    <div>
      {loading ? <p>Loading...</p> : <p>{quote}</p>}
    </div>
  );
}

How It Works

  1. useEffect runs when the component mounts.
  2. The fetchQuote function makes an async call to an API.
  3. await pauses until the data is returned.
  4. setQuote updates the state with the result.
  5. Loading and error states are handled properly.

πŸ“Œ Best Practices

  • Always handle errors using try/catch.
  • Use finally to stop loading even if fetch fails.
  • Don't use async directly inside useEffect; create an inner async function.
Try Live Async Example

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review