Async code in an effect means it could run after the component gets unmounted.
If what bothers you is just the warning about the setState when unmounted, this should go away with React 18 version. (I can't have a link to that, if anybody bothers to edit!)
If you want to avoid async code to run in an effect after component gets unmounted, what you could do is cancel the promises:
useEffect(() => {
if (inView && !fetching.current) {
setLoading(true);
fetching.current = true;
let fetchPromise;
try {
const delayPromise = delay(delayMs).then(async () => {
const country = await fetchData();
setMoreCountriesFunc(country);
fetching.current = false;
});
catch() {
// Manage abortion case if necessary
}
return () => {
delayPromise.cancel()
fetchPromise && fetchPromise.cancel()
}
}
}, [inView, setMoreCountriesFunc, fetchData]);
That would need both your promises to support cancel
operation. For fetch operations, the promise returned by your fetchData
should probably implement AbortController
as explained here, and the delay
also.
This is what is suggested in the react docs here
Otherwise, IMHO you can always have a ref that would hold the mount status and use this as a condition to stop running the effect.
You could refactor as following:
const isMountedRef = useRef(true)
useEffect(() => () => { isMountedRef.current = false }, [])
useEffect(() => {
if (inView && !fetching.current) {
setLoading(true);
fetching.current = true;
delay(delayMs).then(async () => {
// Avoid useless fetch
if (!isMountedRef.current) return
const country = await fetchData();
// Avoid setting state on unmounted component
if (!isMountedRef.current) return
setMoreCountriesFunc(country);
fetching.current = false;
});
}
}, [inView, setMoreCountriesFunc, fetchData]);
Note: why holding the loading state in both a ref and a state? The later should be enough if you need a re-render, or the former if you don't?
delay
, does it returns an object using which you can cancel it? If so you can do something likereturn () => {delayObj.cancel()}
inuseEffect
return