React Async Component Example

Creating a Async Image component using useFetch method of React Async to fetch and render the data asynchronously.

Javascript




// Filename - App.js
 
import { useFetch } from "react-async";
const Image = () => {
    let imgSrc = "";
    const { data, error } = useFetch(
        `https://dog.ceo/api/breeds/image/random`,
        {
            headers: { accept: "application/json" },
        }
    );
    if (error) return error.message;
    if (data) imgSrc = data.message;
    console.log(data);
    return (
        <>
            <img src={imgSrc} alt="image" />
        </>
    );
};
 
function App() {
    return (
        <div className="App">
            <h1>Image using the Dog API</h1>
            <Image />
        </div>
    );
}
 
export default App;


Output: Go to your browser and open http://localhost:3000/, a picture of a dog with the heading “Image using the Dog API” will appear.



What are Async Components ?

Async Components are the ones that load data only when required instead of loading it at compile time in the initial rendering. These are also called lazy-loaded components that improve performance by loading components asynchronously.

Table of Content

  • What are Async Components
  • What is React Async
  • Prerequisite
  • React Async Component Example:

Similar Reads

Async Components in React

Async Components are also referred to as asynchronous components. Async components work as a wrapper and update the state only when required preventing unnecessary loading....

What is React Async ?

React Async is a module that is extensively used for fetching data from the backend. React Async’s metal model is component first. By using it we can perform data loading at the component level itself. Such a component is called an async component....

React Async Component Example:

Creating a Async Image component using useFetch method of React Async to fetch and render the data asynchronously....