Skip to content

Instantly share code, notes, and snippets.

@Phryxia
Created September 23, 2024 15:42
Show Gist options
  • Save Phryxia/049affe0234e0b8b1c100f44819934b3 to your computer and use it in GitHub Desktop.
Save Phryxia/049affe0234e0b8b1c100f44819934b3 to your computer and use it in GitHub Desktop.
Convenient useAsyncEffect for react.js
import { useEffect } from 'react';
type UseAsyncEffectCleaner = () => Promise<void> | void;
type UseAsyncEffectCallback = () =>
| Promise<UseAsyncEffectCleaner | void>
| UseAsyncEffectCleaner
| void;
export function useAsyncEffect(fn: UseAsyncEffectCallback, deps?: any[]) {
return useEffect(() => {
const ret = fn();
if (!ret) return;
if (typeof ret === 'function') {
return () => void ret();
}
return () => void ret.then((cleaner) => cleaner?.());
}, deps);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment