Languages
[Edit]
EN

React - async useEffect

3 points
Created by:
Vanessa-Drake
718

In this article we would like to show you how to use async useEffect in React.

Note: to see how to create custom async useEffect hook read this article.

In below example we create additional internal async function for useEffect call. We can't use async directly because it will make the callback function return a Promise instead of cleanup function.

Runnable example:

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from "react";
// import ReactDOM from "react-dom";

const App = () => {
    const [response, setResponse] = React.useState();
    React.useEffect(() => {
      	let mounted = true; // to let make state changes only when component is mounted
        ; (async () => {
            const requestText = 'hello';
            try {
                const response = await fetch(`/examples/echo?text=${encodeURIComponent(requestText)}`);
                const responseText = await response.text();
              	if (mounted) {
                	setResponse(`Response: ${responseText}`);
                }
            } catch (error) {
              	if (mounted) {
              		setResponse('Request error!');
                }
            }
        })();
      	return () => {
        	mounted = false;
        };
    }, []);
    return (
      <div>{response}</div>
    );
};

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

Note:

So do not use following construction because it doesn't allow us to detect component unmount action:

React.useEffect(async () => {...}, []);
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 - async useEffect
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