How to handle asynchronous operations in function based components in React.js?

How to use class based components in React.js? »

Now, let’s assume you want to see the active hours in place of “Hello World” in the web browser instead of console window. You may make some changes to the code and expect it to work (setTimeout() is an asynchronous operation):

import React from 'react';
import ReactDOM from 'react-dom';

const App = () => {
    const getHours = () => {
       const currentHours = new Date().getHours();
       return currentHours;
    }

    const getTime = () => {
       setTimeout(() => {
           const hours = getHours().toString(); console.log(hours);
           return hours;
       },
       3000);
    }

    return <div>
       Current hour is: {getTime()}
    </div>;
};

ReactDOM.render(
 <App />,
 document.querySelector('#root')  
);

getTime() is a function that should return the current hour to be used inside the JSX in the return statement. However, if you run the app, it’ll only show “Current hour is:”.

This is because of the order of operations and rendering in React.js. Right now, this is how it works:

  1. getTime() is called from the return statement of App component
  2. By this time, “Current hour is:” is already rendered to the browser and getTime() would take 3 seconds to return the hours count as setTimeout() is an asynchronous operation
  3. The return statement is not re-rendered when the getTime() returns the hours count

Therefore, you see that there should be a way to re-render the JSX that is available on the browser, once an API request is completed. This is why we need a Class Based Component as opposed to a Function Based Component. It is not possible to handle a asynchronous operation using a functional component.

Leave a Comment