Today I Learned

useSafeDispatch custom hook

November 21, 2022

To dispatch a function only when the component is mounted and will be cancelled when unmounted.

import * as React from 'react'

function useSafeDispatch(dispatch) {
  const mounted = React.useRef(false)

  React.useLayoutEffect(() => {
    mounted.current = true
    return () => {
      mounted.current = false
    }
  }, [])

  return React.useCallback(
    (...args) => (mounted.current ? dispatch(...args) : undefined),
    [dispatch],
  )
}

© 2026 - Written by Vuong Vu. Connect with me on LinkedIn.