How to wait for a ReactJS component to finish updating ?
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. 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.
Creating 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:
Project structure: It will look like this.
Step 3: Write down the following code in index.js.
Step 4: Here we are using the Axios library for fetching API data, we need to install that by using the command from the root directory.
npm install axios
Step 5: Start your component in “loading mode”.
We will use the concept of conditional rendering and useEffect to wait for a ReactJS component to finish updating. With the use of conditional rendering of “Loading” text and by using useState we achieve the “loading mode” state of the component. useEffect uses a function that will be called after the DOM is updated. This way the time isLoading is false and we are in a waiting state so that in that time whole component gets finally updated. SetTimeout() is used to simulate the delay in the loading so that we can observe the loading state. This way we create a loading state in the application.
Step to run the application: Open the terminal and type the following command.
Output: When we run the above code.
Please Login to comment...