nurbol.dev

nurbol.dev

Safe useReducer dispatch

To make sure that useReducer dispatch runs only if component is mounted we can obtain it through useSafeDispatch hook

function useSafeDispatch(dispatch) {
    const mountedRef = useRef(false)
    
    useLayoutEffect(() => {
        mountedRef.current = true

        return () => {
            mountedRef.current = false
        }
    })

    return useCallback(
        (...args) => {
            if (mountedRef.current) {
                dispatch(...args)
            }
        },
        [dispatch],
    )
}