Andrew's Digital Garden

Creating a safe dispatch function

When dealing with async code, the dispatch function often fires at the end of a promise, where the component/reducer its working with may already been unmounted. If this is the case, an error is thrown, as React is trying to act on state for a component that does not already exist. To solve this, a wrapper around the dispatch function can be used:

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) : void 0), [dispatch], ) }

[[20211203041953-dispatch-setstate-stable-react]]

[[react]]

Creating a safe dispatch function