insomnia/packages/insomnia-app/app/ui/hooks/use-safe-reducer-dispatch.ts
2021-06-23 12:40:48 -04:00

15 lines
378 B
TypeScript

import { useCallback } from 'react';
import { useMountedState } from 'react-use';
export const useSafeReducerDispatch = <A>(dispatch: (action: A) => void) => {
const isMounted = useMountedState();
const safeDispatch = useCallback<typeof dispatch>((...args) => {
if (isMounted()) {
dispatch(...args);
}
}, [dispatch, isMounted]);
return safeDispatch;
};