Languages
[Edit]
EN

React - custom async useEffect hook

9 points
Created by:
Kadeem-Craig
516

In this article, we would like to show you how to create your own async useEffect hook function in React.

By default, React doesn't provide that kind of function, but there is a simple way how to create your own one.

Quick solution:

The main advantage of that kind function is the possibility to use await keyword when we do AJAX or other async operations with useEffect, that makes code more readable. In the below approach, we can use easily isInvalid() function that checks if the component state should be modified still because of current dependencies - after async AJAX request is done current conditions can be incorrect to bind result (different dependency values).

 

useAsyncEffect with AJAX example

Edit

In this section, we would like to show you how to use useAsyncEffect with fetch function (with AJAX requests).

Note: in below example we can check isInvalid() status always after any method with await keyword is called to finish useEffect logic execution in proper way, but most important is to do not change state on unmounted component what we do.

useAsyncEffect as timer example

Edit

async useEffect can be easy way used to write own timer logic. In the below example we used sleep() method that slows down useAsyncEffect function for 1 second.

Alternative titles

  1. React - custom useAsyncEffect hook
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - custom async useEffect hook
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join