3

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.

  • 2
    What's the problem with it showing twice in the console? What's the actual problem you're trying to solve? – msmoore Aug 29 '22 at 07:56
  • https://stackoverflow.com/questions/61254372/my-react-component-is-rendering-twice-because-of-strict-mode I think there is no way without removing the strict mode https://reactjs.org/docs/strict-mode.html – zain ul din Aug 29 '22 at 08:01
  • This `StrictMode` render behavior is only occurring in dev, not prod. This change was introduced in-order to help devs catch possible bugs relating to their use of `useEffect`, etc.. In other words, this behavior can not be adjusted without removing `StrictMode`. The question is what are you trying to achieve and why do you need to avoid it when taking into account that it doesn't render twice in prod, as mentioned. – tomleb Aug 29 '22 at 08:02
  • The problem with this is that I am calling a code send function which sends a user a verification code via SMS and I have to call it once to avoid charging too much – Daniciuc Razvan Aug 29 '22 at 08:16

1 Answers1

5

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
Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90