Issue
I am new to TypeScript. I got an error when I tried to use useEffect
in TypeScript in React,
Argument of type '() => () => boolean' is not assignable to parameter of type 'EffectCallback'.
Why am I getting this error?
Here is my code:
const useIsMounted = () => {
const isMounted = React.useRef(false);
React.useEffect(() => {
isMounted.current = true;
return () => isMounted.current = false;
}, []);
return isMounted;
};
Solution
The function of useEffect
(EffectCallback
type) should return void
or () => void | undefined
.
function useEffect(effect: EffectCallback, deps?: DependencyList): void;
type EffectCallback = () => (void | (() => void | undefined));
In your case, you are returning void => boolean
:
// void => boolean
return () => (isMounted.current = false);
To fix it, add scope to the statement of the cleaning function:
const useIsMounted = () => {
const isMounted = React.useRef(false);
React.useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
return isMounted;
};
Answered By - Dennis Vash
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.