Nikul Panchal
Nikul Panchal

Reputation: 1673

Getting error: "Argument of type '() => () => boolean' is not assignable to parameter of type 'EffectCallback'"

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

Upvotes: 28

Views: 23607

Answers (2)

Kacpero
Kacpero

Reputation: 9

Just wrap return () => {isMounted.current = false}. Shortcut you used looks like this return () => { return isMounted.current = false;} so you return boolean value which is incorrect.

Upvotes: 0

Dennis Vash
Dennis Vash

Reputation: 53964

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

Upvotes: 59

Related Questions