Created
January 30, 2021 14:37
-
-
Save danieljpgo/28947d01a46065a9682e8185908d8de6 to your computer and use it in GitHub Desktop.
useSafeDispatch hook
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
export const useSafeDispatch = dispatch => { | |
const mountedRef = React.useRef(false) | |
React.useLayoutEffect(() => { | |
mountedRef.current = true | |
return () => { | |
mountedRef.current = false | |
} | |
}, []) | |
return React.useCallback( | |
(...args) => { | |
if (mountedRef.current) { | |
dispatch(...args) | |
} | |
}, | |
[dispatch], | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment