How to wait for a ReactJS component to finish updating ?
Last Updated :
02 Nov, 2023
To wait for a ReactJS component to finish updating, we use a loading state in our react application by use of the conditional rendering of the component.
Approach
This can be achieved by the use of the useState and useEffect hooks in the functional components. With the help of the state, we make sure at initial it is false and after the update is done it becomes true. This way conditional rendering will render the component only after the update is finished. We use useEffect hook to check the update status and load all the updates when the first time application is rendered.
Let’s see an example to demonstrate the concept.
Steps to create React Application
Step 1: Create a React application using the following command
npx create-react-app example
Step 2: After creating your project folder i.e. example, move to it using the following command
cd example
Project structure:
Steps to install axios: Use this command in the terminal
npm i axios
The updated dependencies in package.json file will look like:
{
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.5.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
}
Example: We will show loading state while fetching the data from the given api and when tha loading is completed the data will be rendered in required format.
App.js
import React, { useEffect, useState } from "react" ;
import axios from "axios" ;
function App() {
const [isLoading, setLoading] = useState( true );
const [images, setImages] = useState([]);
useEffect(() => {
setTimeout(() => {
axios
.get(
)
.then((response) => {
console.log(response.data.photos);
setImages(response.data.photos);
setLoading( false );
});
}, 3000);
}, []);
if (isLoading) {
return (
<div
style={{
display: "flex" ,
flexDirection: "column" ,
alignItems: "center" ,
justifyContent: "center" ,
height: "100vh" ,
}}
>
Loading the data{ " " }
{console.log( "loading state" )}
</div>
);
}
return (
<div
style={{
display: "flex" ,
flexDirection: "column" ,
alignItems: "center" ,
justifyContent: "center" ,
minHeight: "100vh" ,
}}
>
<h1 style={{ color: "green" }}>
{ " " }
GeeksforGeeks
</h1>
<div
style={{
display: "flex" ,
flexDirection: "row" ,
flexWrap: "wrap" ,
padding: "2%" ,
}}
>
{images.map((e) => {
return (
<div
style={{
width: "15rem" ,
margin: "1%" ,
}}
>
<img
style={{ width: "200px" }}
alt={e.title}
src={e.url}
/>
<h3>{e.title}</h3>
</div>
);
})}
</div>
</div>
);
}
export default App;
|
Step to run the application: Open the terminal and type the following command.
npm start
Output: This output will be visible on http://localhost:3000/ on browser window.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...