Skip to content
← Snippets

useSafeAsync Hook

Safely avoid setting state on unmounted components.

Sep 5, 2022 · 1 min read

When you perform asynchronous actions (like fetching data), React will warn if you try to setState after a component has unmounted.

useSafeAsync provides a safe ref you can check before updating state.


Code

useSafeAsync.ts
import { useRef, useEffect } from 'react';
 
export function useSafeAsync() {
  const isMounted = useRef(true);
 
  useEffect(() => {
    return () => {
      isMounted.current = false;
    };
  }, []);
 
  return isMounted;
}
useSafeAsync Hook | Viren Soni | Software Engineer