-
-
Save aishwarya257/d69f540c065e2387ef32e1e29c294df6 to your computer and use it in GitHub Desktop.
useSafeDispatch function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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