Created
January 9, 2022 21:25
-
-
Save oguzkaracar/2ba1bb3dcff2f58956ad56c47d77c9e7 to your computer and use it in GitHub Desktop.
Safe dispatch funtion - just dispatch it when component is mounted
This file contains hidden or 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
const useSafeDispatch = dispatch => { | |
/* Figure out component is unmounted */ | |
const mountedRef = React.useRef(false) | |
/* this function going to be called as soon we mounted, without waiting the browser paint the screen */ | |
React.useLayoutEffect(() => { | |
mountedRef.current = true | |
/* called when as soon we unmounted without waiting the browser paint the screen */ | |
return () => { | |
mountedRef.current = false | |
} | |
}, []) | |
/* Unmount - mount control */ | |
return React.useCallback( | |
(...args) => { | |
if (mountedRef.current) return dispatch(...args) | |
}, | |
[dispatch], | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment