# Why useEffect is running twice in React

If you have created a new project recently using [Create React App](https://reactjs.org/docs/create-a-new-react-app.html)
or upgraded to React version 18, you will see that the [useEffect](https://www.codingdeft.com/posts/react-useeffect-hook/) hook gets executed twice in development mode.

If you are new to useEffect hook, you can read one of my previous articles: [a complete guide to useEffect hook](https://www.codingdeft.com/posts/react-useeffect-hook/).

## Replicating the issue

Create a new react app using the following command:

```bash
npx create-react-app react-use-effect-twice
```

Update `App.js` with the following code:

```jsx
import { useEffect } from "react"

function App() {
  useEffect(() => {
    console.log("useEffect executed (component mounted)")
  }, [])

  return <div className="App"></div>
}

export default App
```

Here we have a useEffect hook and we are logging a message inside it.

If you run the application and open the browser console, you will see the message is being displayed twice.

![two messages in console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2pqecvrupagpvi30xu6b.png) 

## Understanding the issue

In [StrictMode](https://reactjs.org/docs/strict-mode.html), starting from React 18, in development mode, the effects will be mounted, unmounted, and mounted again.

This happens only in development mode, not in production mode.

This was added to help React in the future to introduce a feature where it can add or remove a section of the UI while preserving the state. For example, while switching between tabs, preserving the state of the previous tab helps in preventing unnecessary execution of effects like API calls.

We can confirm the behavior by adding a cleanup function to the useEffect hook:

```jsx
import { useEffect } from "react"

function App() {
  useEffect(() => {
    console.log("useEffect executed (component mounted)")
    return () => {
      console.log("useEffect cleanup (component unmounted)")
    }
  }, [])

  return <div className="App"></div>
}

export default App
```

If you run the application, you will see the following messages in the browser console:

![unmount message in console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o0plm2ogqm9zj30sg6or.png)
 

## Fixing the issue

If you have read the previous section, this is not really an issue. Hence it doesn't need any fixing.

If you still want to avoid useEffect being called twice, you can remove the `<StickMode>` tag from the `index.js` file.

