0
Hours
0
Minutes
0
Seconds

How to create useAsync hook in React.js? | JavaScript Interview Question | Frontend Problem Solving | Custom React Hooks
@Devtools Tech

247

React Hooks are a new addition in React 16.8. They let us use state and other React features without writing a class.

Often there is a lifecycle of an async request in our components. We show a loading indicator before rendering the results and show an error message if the request fails or on some other error. At times, we want to disable the submit button of the form when submission is pending and then display error or success message on completion.

We can use multiple useState to manage this or we can follow a better way where we abstract this logic and make it reusable utility as a custom hook called useAsync. The hook takes an async function as input and returns the following:

  1. value: final result
  2. error: actual error object captured if any error during entire process
  3. status: current state of the hook. It could either one of idle, pending, success, and error.
  4. execute: function to initiate the execution of callback passed to useAsync hook.
function fetchPosts() {
  ...
}

...

const { value, error, status, execute } = useAsync(fetchPosts); 
...

So, in this question, you need to create a custom hook useAsync the implements the above mentioned functionalities.