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: