Question:
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:I know about the StrictMode, but I don’t want to disable it.
If everyone would have an opinion, would be great.
Thanks.
Best Answer:
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 inuseEffect
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
If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com
Leave a Review