Why is my function being called twice in React?

Its because your app component is a wrap in StrictMode.

<React.StrictMode>
  <App />
</React.StrictMode>,

If you are using create-react-app then it is found in index.js

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 (which wouldn’t be the case if an async render was aborted and later restarted). If your setState updaters are pure functions (as they should be) then this shouldn’t affect the logic of your application.

https://github.com/facebook/react/issues/12856#issuecomment-390206425

Leave a Comment