reactjsuse-effectusecallback

UseEffect is called twice in component mounting even when using useCallback


I have the following problem. I have a component which needs to call an API when mounted. I do the call in a useCallback like this:

const sendCode = useCallback(() => {
        console.log('InsideSendCode');
    }, []);

And then I call this function inside of a useEffect like this:

useEffect(() => {
        sendCode();
    }, [sendCode]);

The thing is that, even by using the useCallback, the message is displayed in the console twice and I've seen that this would be the only option.

I know about the StrictMode, but I don't want to disable it.

If everyone would have an opinion, would be great.

Thanks.


Solution

  • That is standard behavior in Strict mode:

    When Strict Mode is on, React mounts components twice (in development only!) to stress-test your Effects.

    Initially react was only calling render twice to detect if you have some side effects, but afterwards they also added calling effects twice during initial mount, to make sure you have implemented cleanup functions well. This only applies to strict mode AFAIK.

    I suggest you read the link above. You have few options: