Skip to content

Instantly share code, notes, and snippets.

@danieljpgo
Created January 30, 2021 14:37
Show Gist options
  • Save danieljpgo/28947d01a46065a9682e8185908d8de6 to your computer and use it in GitHub Desktop.
Save danieljpgo/28947d01a46065a9682e8185908d8de6 to your computer and use it in GitHub Desktop.
useSafeDispatch hook
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