Merge branch 'fix-typo-drive' into 'main'
[ProtonMail-WebClient.git] / packages / pass / hooks / useEnsureMounted.ts
blob0d0700907b56d4146821ac75d9dcb8ab295f8af7
1 import { useCallback, useState } from 'react';
3 import useIsMounted from '@proton/hooks/useIsMounted';
4 import type { Callback, Maybe } from '@proton/pass/types';
6 export const useEnsureMounted = () => {
7     const isMounted = useIsMounted();
8     return useCallback(
9         <T extends Callback>(fn: T) =>
10             ((...args: Parameters<T>): Maybe<ReturnType<T>> => {
11                 if (isMounted()) return fn(...args);
12             }) as T,
13         []
14     );
17 export const useMountedState = <T>(initial: T) => {
18     const [state, setState] = useState<T>(initial);
19     const ensureMounted = useEnsureMounted();
20     const setStateSafe = useCallback(ensureMounted(setState), []);
22     return [state, setStateSafe] as const;