Skip to content

Instantly share code, notes, and snippets.

@oguzkaracar
Created January 9, 2022 21:25
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 oguzkaracar/2ba1bb3dcff2f58956ad56c47d77c9e7 to your computer and use it in GitHub Desktop.
Save oguzkaracar/2ba1bb3dcff2f58956ad56c47d77c9e7 to your computer and use it in GitHub Desktop.
Safe dispatch funtion - just dispatch it when component is mounted
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