ref – https://stackoverflow.com/questions/50819162/why-is-my-function-being-called-twice-in-react
When you create a project using create-react-app, it puts the App component inside React.StrictMode tags.
1 2 3 |
<React.StrictMode> <App /> </React.StrictMode> |
Document says:
Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following methods:
Class component constructor method
The render method
setState updater functions (the first argument)
The static getDerivedStateFromProps lifecycle
The shouldComponentUpdate method
It is expected that setState updaters will run twice in strict mode in development.
This helps ensure the code doesn’t rely on them running a single time.
If your setState updaters are pure functions (as they should be) then this shouldn’t affect the logic of your application.
If you do not want this effect, do this:
1 2 3 4 |
<> <App /> <MyPureComponent /> </>, |