Skip to content

Instantly share code, notes, and snippets.

@aishwarya257
Created August 15, 2021 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aishwarya257/d69f540c065e2387ef32e1e29c294df6 to your computer and use it in GitHub Desktop.
Save aishwarya257/d69f540c065e2387ef32e1e29c294df6 to your computer and use it in GitHub Desktop.
useSafeDispatch function
import { Dispatch, useCallback, useLayoutEffect, useRef } from "react";
export function useSafeDispatch<T>(dispatch: Dispatch<T>) {
const mounted = useRef(false);
useLayoutEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
return useCallback((arg:T) => {
if(mounted.current) {
dispatch(arg)
}
}, [dispatch]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment