According to breaking changes in react 18, hidden components cannot trigger the useEffect hook. See https://github.com/facebook/react/pull/22114 Since the warning is no longer triggered, we can safely remove the workaround.main
parent
32ed298d27
commit
83a0210ffa
23 changed files with 77 additions and 197 deletions
@ -1,30 +0,0 @@ |
|||||||
import { useEffect, useRef } from 'react'; |
|
||||||
|
|
||||||
// Allow any function as callback in the protect function.
|
|
||||||
// Could be used to wrap async callbacks to prevent them from running after
|
|
||||||
// component unmount.
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
type AnyFunction = (...args: any[]) => any; |
|
||||||
|
|
||||||
type ProtectFunction = <F extends AnyFunction>( |
|
||||||
fn: F, |
|
||||||
...args: Parameters<F> |
|
||||||
) => ReturnType<F>; |
|
||||||
|
|
||||||
const useProtect = (): { protect: ProtectFunction } => { |
|
||||||
const isComponentMountedRef = useRef<boolean>(true); |
|
||||||
|
|
||||||
useEffect( |
|
||||||
() => () => { |
|
||||||
isComponentMountedRef.current = false; |
|
||||||
}, |
|
||||||
[], |
|
||||||
); |
|
||||||
|
|
||||||
return { |
|
||||||
protect: (fn, ...args) => |
|
||||||
isComponentMountedRef.current ? fn(...args) : undefined, |
|
||||||
}; |
|
||||||
}; |
|
||||||
|
|
||||||
export default useProtect; |
|
@ -1,34 +0,0 @@ |
|||||||
import { Dispatch, SetStateAction, useMemo, useState } from 'react'; |
|
||||||
|
|
||||||
import useProtect from './useProtect'; |
|
||||||
|
|
||||||
type SetStateFunction<S> = Dispatch<SetStateAction<S>>; |
|
||||||
|
|
||||||
type SetStateParameters<S> = Parameters<SetStateFunction<S>>; |
|
||||||
|
|
||||||
type SetStateReturnType<S> = ReturnType<SetStateFunction<S>>; |
|
||||||
|
|
||||||
const useProtectedState = <S>( |
|
||||||
initialState: S | (() => S), |
|
||||||
protect?: ( |
|
||||||
fn: SetStateFunction<S>, |
|
||||||
...args: SetStateParameters<S> |
|
||||||
) => SetStateReturnType<S>, |
|
||||||
): [S, SetStateFunction<S>] => { |
|
||||||
const { protect: defaultProtect } = useProtect(); |
|
||||||
|
|
||||||
const [state, setState] = useState<S>(initialState); |
|
||||||
|
|
||||||
const pfn = useMemo( |
|
||||||
() => protect ?? defaultProtect, |
|
||||||
[defaultProtect, protect], |
|
||||||
); |
|
||||||
|
|
||||||
return [ |
|
||||||
state, |
|
||||||
(...args: SetStateParameters<S>): SetStateReturnType<S> => |
|
||||||
pfn(setState, ...args), |
|
||||||
]; |
|
||||||
}; |
|
||||||
|
|
||||||
export default useProtectedState; |
|
Loading…
Reference in new issue