Advertisement
djbob2000

Untitled

Dec 23rd, 2024
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //src/hooks/useAsyncEffect.ts
  2. import { DependencyList, useEffect, useRef } from "react";
  3.  
  4. export function useAsyncEffect(
  5.     effect: () => Promise<void | (() => void | Promise<void>)>,
  6.     dependencies: DependencyList = [],
  7. ) {
  8.     const isMounted = useRef(false);
  9.     const cleanupFn = useRef<void | (() => void | Promise<void>)>();
  10.  
  11.     useEffect(() => {
  12.         isMounted.current = true;
  13.  
  14.         const executeEffect = async () => {
  15.             try {
  16.                 cleanupFn.current = await effect();
  17.             } catch (err) {
  18.                 if (isMounted.current) {
  19.                     throw err;
  20.                 }
  21.             }
  22.         };
  23.  
  24.         executeEffect();
  25.  
  26.         return () => {
  27.             isMounted.current = false;
  28.             if (cleanupFn.current) {
  29.                 cleanupFn.current();
  30.             }
  31.         };
  32.     }, [effect, dependencies]);
  33. }
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement