React useMemo x is not a function

3.3k Views Asked by At

I have a react app with hooks where I needed to replicate the behavior of componentWillMount. I read here that for this purpose useMemo could be used so my code roughly looks like this

const Component = ({
   some props,
    ...props
}) => {
  
    useEffect(() => {
       handleTranslations();
    }, []);

    useMemo(() => {
        // componentWillMount events
            handleCheckSession();
    }, []);
    const handleCheckSession = async() => {
        await props.checkSession();
        await handleWebNotificationsFetch();
    };

    const handleWebNotificationsFetch = async() => {
        some code here
    };

   const handleTranslations = () => {
   some code 
   };

In this case I can see an error in the console saying that handleCheckSession is not a function. If I move useMemo below the handleCheckSession declaration or invoke the methods (coming from props) directly inside the hook everything is ok. What is the reason for this behavior since useEffect has no problem finding and invoking handleTranslations or other functions declared below? Is this because useEffect is executed during rendering and useMemo before?

2

There are 2 best solutions below

0
Patri Bottino On

execute in other order the useMemo after the function handleCheckSession example:

 const handleCheckSession = async() => {
        await props.checkSession();
        await handleWebNotificationsFetch();
    };
useMemo(() => {
        // componentWillMount events
            handleCheckSession();
    }, []);
0
fruitloaf On

in my case the error was caused because I was CALLING the function:

<div>{functionName()}</div>  = error, functionName is NOT a function

CHANGE TO:

<div>{functionName}</div> = works fine

so basically remove the () brackets, and it works