Daniciuc Razvan
Daniciuc Razvan

Reputation: 65

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.

Upvotes: 3

Views: 1276

Answers (1)

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

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:

  • if the API call you are making is GET request which simply gets some information, let it be called twice, there is no much harm.
  • You could use a ref to keep track if it is first mount or not, and then correspondingly make request in useEffect only if this is first mount. Although this approach is not listed in official recommendations, I suppose you can use it as a last resort; it was documented at some point. Dan Abramov also mentioned you could use it as last measure, just they don't encourage it.
  • disable Strict mode

Upvotes: 5

Related Questions