Open In App

What are Async Components ?

Last Updated : 28 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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.

Async components in React can be implemented using the below React-Async Module.

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. 

Dependencies for React Async Components

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-async": "^10.0.1",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

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.

React Async Components Example - output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads