Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //src/hooks/useAsyncEffect.ts
- import { DependencyList, useEffect, useRef } from "react";
- export function useAsyncEffect(
- effect: () => Promise<void | (() => void | Promise<void>)>,
- dependencies: DependencyList = [],
- ) {
- const isMounted = useRef(false);
- const cleanupFn = useRef<void | (() => void | Promise<void>)>();
- useEffect(() => {
- isMounted.current = true;
- const executeEffect = async () => {
- try {
- cleanupFn.current = await effect();
- } catch (err) {
- if (isMounted.current) {
- throw err;
- }
- }
- };
- executeEffect();
- return () => {
- isMounted.current = false;
- if (cleanupFn.current) {
- cleanupFn.current();
- }
- };
- }, [effect, dependencies]);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement