React.StrictMode combined with useState causes component to render twice
See original GitHub issueDo you want to request a feature or report a bug? Bug (maybe)
What is the current behavior?
If wrapped in React.StrictMode and a function component contains a call to useState
, the function (render) is called twice - even if the state setter is never called.
If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. https://codesandbox.io/s/lyw9514j4q (please see console)
What is the expected behavior? I would expect it to only render once.
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React? 16.8.3 in Chrome on macOS Mojave; requires hooks so not tested with previous versions.
This may be related to https://github.com/facebook/react/issues/12961 - but note that nowhere am I setting state (only initializing it).
If this is expected behavior please feel free to close. Thank you!
Issue Analytics
- State:
- Created 5 years ago
- Reactions:32
- Comments:22 (5 by maintainers)
It’s an intentional feature of the StrictMode. This only happens in development, and helps find accidental side effects put into the render phase. We only do this for components with Hooks because those are more likely to accidentally have side effects in the wrong place.
Sorry, I know this was closed, but you say
but if your component uses a class – even if it’s stateless – it also renders twice. Threw me for a loop today trying to figure out why my component wasn’t working properly.