insomnia/packages/insomnia-app/app/ui/hooks/use-safe-reducer-dispatch.ts

15 lines
378 B
TypeScript
Raw Normal View History

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;
};