--

I didn't understand the question.

About variables and references: it is correct to share variables via closure between the useEffect hook function and the clean up function.

About the fact that if you do something asynchronous the cleanUp function can be executed before the async code is terminated, the solution is not straight forward. The idea is to block the async code and cause it to rise an exception or return a rejected promise. This way it is possible to avoid running the code after the async one.

For example if you use Axios, you can abort fetches. So you can get a rejected promise of the http request and so execute the code after the request only if the fetch was successful.

Example:

useEffect(() => {
let unsubscribe = () => null;
const abortSource = axios.CancelToken.source();
async function fetchData() {
try {
await apifetch({}, abortSource.token);
unsubscribe = dummySubscriber();
} finally {}
}
fetchData(); return () => {
abortSource.cancel();
unsubscribe();
};
}, []);

--

--

Andrea Koutifaris
Andrea Koutifaris

Responses (1)