useEffect firing twice in React 18
Tags: react, webdev, javascript
Published: 2022-07-30 18:22:00

## Gist

Acoording to [React 18 Changelog](https://github.com/facebook/react/blob/main/CHANGELOG.md#1800-march-29-2022):

> In the future, React will provide a feature that lets components preserve state between unmounts. To prepare for it, React 18 introduces a new development-only check to Strict Mode. React will automatically unmount and remount every component, whenever a component mounts for the first time, restoring the previous state on the second mount. If this breaks your app, consider removing Strict Mode until you can fix the components to be resilient to remounting with the existing state.

So, in short, When Strict Mode is on, React mounts components twice (**in development only!**) to check and let you know it has bugs. This is in development only and has **no effect** in code running in production.

If you just came here to "know" why your effects are being called twice that's it, that's the gist. You can spare reading this whole article, and [go fix your effects](https://beta.reactjs.org/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development)
However, you can stay here and know some of the nuances.

## But first, what is an effect?

[According to beta react docs](https://beta.reactjs.org/learn/synchronizing-with-effects):

> Some components need to synchronize with external systems. For example, you might want to control a non-React component based on the React state, set up a server connection, or send an analytics log when a component appears on the screen. _Effects let you run some code after rendering so that you can synchronize your component with some system outside of React._

The _after rendering_ part here is quite important. Therefore, you should keep this in mind before adding an effect to your component. For example, you might be setting some state in an effect based on a local state or a prop change.

```jsx
function UserInfo({ firstName, lastName }) {
  const [fullName, setFullName] = useState('')

  // 🔴 Avoid: redundant state and unnecessary Effect
  useEffect(() => {
    setFullName(`${firstName} ${lastName}`)
  }, [firstName, lastName])

  return <div>Full name of user: {fullName}</div>
}
```

Just don't. Not only it is unnecessary, but it will cause an unnecessary second re-render when the value could've been calculated [during render](https://beta.reactjs.org/learn/render-and-commit)

```jsx
function UserInfo({ firstName, lastName }) {
  // ✅ Good: calculated during initial render
  const fullName = `${firstName} ${lastName}`

  return <div>Full name of user: {fullName}</div>
}
```

"But what if calculating some value during a render is not as cheap as our `fullName` variable here ?" Well, in that case, you can [memoize an expensive calculation](https://reactjs.org/docs/hooks-reference.html#usememo). You still don't have any need to use an Effect here

```jsx
function SomeExpensiveComponent() {
  // ...

  const data = useMemo(() => {
    // Does no re-run unless deps changes
    return someExpensiveCalculaion(deps)
  }, [deps])

  // ...
}
```

This tells React to not re-calculate `data` unless `deps` changes. You only need to do this even when `someExpensiveCalculaion` is quite slow (say takes ~10 ms to run). But it's up to you. First see is it fast enough without a `useMemo` then build up from there. You can check the time it takes to run a piece of code using [`console.time`](https://developer.mozilla.org/en-US/docs/Web/API/console/timeEnd#examples) or [`performance.now`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now#examples):

```js
console.time('myBadFunc')
myBadFunc()
console.timeEnd('myBadFunc')
```

You can see log like `myBadFunc: 0.25ms` or so. You can now decide whether to use `useMemo` or not. Also, even before using [`React.memo`](https://reactjs.org/docs/react-api.html#reactmemo), you should first [read this awesome article](https://overreacted.io/before-you-memo/) by [Dan Abramov](https://twitter.com/dan_abramov)

## What is useEffect

`useEffect` is a [react hook](https://reactjs.org/docs/hooks-effect.html) that lets you to run side effects in your components. As discussed previously, effects run after a render and are caused by rendering itself, rather than by a particular event. (An event can be a user icon, for example, clicking a button). Hence `useEffect` should be only used for synchronization since it is not just fire-and-forget. **The useEffect body is "reactive" in the sense whenever any dependencies in the dependency array change, the effect is re-fired**. This is done so that the result of running that effect is always consistent and synchronized. But, as seen, this is not desirable.

It can be very tempting to use an effect here and there. For example, you want to filter a list of items based on a specific condition, like "cost less than ₹500". You might think to write an effect for it, to update a variable whenever the list of items changes:

```jsx
function MyNoobComponent({ items }) {
  const [filteredItems, setFilteredItems] = useState([])

  // 🔴 Don't use effect for setting derived state
  useEffect(() => {
    setFilteredItems(items.filter(item => item.price < 500))
  }, [items])

  //...
}
```

As discussed, it is inefficient. React will be needing to re-run your effects after updating state & calculating and updating UI. Since this time we are updating a state (`filteredItems`), React needs to restart all of this process from step 1! To avoid all this unnecessary calculation, just calculate the filtered list during render:

```jsx
function MyNoobComponent({ items }) {
  // ✅ Good: calculating values during render
  const filteredItems = items.filter(item => item.price < 500)

  //...
}
```

So, [rule of thumb](https://beta.reactjs.org/learn/you-might-not-need-an-effect#updating-state-based-on-props-or-state): When something can be calculated from the existing props or state, don't put it in state. Instead, calculate it during rendering. This makes your code faster (you avoid the extra “cascading” updates), simpler (you remove some code), and less error-prone (you avoid bugs caused by different state variables getting out of sync with each other). If this approach feels new to you, [Thinking in React](https://beta.reactjs.org/learn/thinking-in-react#step-3-find-the-minimal-but-complete-representation-of-ui-state) has some guidance on what should go into the state.

Also, you don't need an effect to handle events. (For example, a user clicking a button). Let's say you want to print a user's receipt:

```jsx
function PrintScreen({ billDetails }) {
  // 🔴 Don't use effect for event handlers
  useEffect(() => {
    if (billDetails) {
      myPrettyPrintFunc(billDetails)
    }
  }, [billDetails])

  // ...
}
```

I am guilty of writing this type of code in past. Just don't do it. Instead, in the parent component (where you might be setting `billDetails` as `setBillDetails()`, on a user's click of button, just do yourself a favor and print it there only):

```jsx
function ParentComponent() {
  // ...

  return (
    // ✅ Good: useing inside event hanler
    <button onClick={() => myPrettyPrintFunc(componentState.billDetails)}>
      Print Receipt
    </button>
  )

  // ...
}
```

The code above is now free of bugs caused by using `useEffect` in the wrong place. Suppose your application remembers the user state on page loads. Suppose user closes the tab because of some reason, and comes back, only to see a print pop-up on the screen. That's not a good user experience.

Whenever you are thinking about whether code should be in an event handler or in `useEffect`, think about why this code needs to be run. Was this because of something displayed to screen, or some action (event) performed by the user. If it is latter, just put it in an event handler. In our example above, the print was supposed to happen because the user clicked on a button, not because of a screen transition, or something shown to the user.

## Fetching Data

One of the most used use cases of effects in fetching data. It is used all over the place as a replacement for `componentDidMount`. Just pass an empty array to array of dependencies and that's all:

```jsx
useEffect(() => {
  // 🔴 Don't - fetching data in useEffect _without_ a cleanup
  const f = async () => {
    setLoading(true)
    try {
      const res = await getPetsList()
      setPetList(res.data)
    } catch (e) {
      console.error(e)
    } finally {
      setLoading(false)
    }
  }

  f()
}, [])
```

We have all seen and probably written this type of code before. Well, what's the issue?

- First of all, `useEffect`s are client-side only. That means they don't run on a server. So, the initial page rendered will only contain a shell of HTML with maybe a spinner
- This code is prone to errors. For example, if the user comes back, clicks on the back button and then again re-opens the page. It is very much possible that the request that the first fired before the second one may get resolved after. So, the data in our state variable will be stale! Here, in the code above, it may not be a huge problem, but it is in the case of constantly changing data, or for eample querying data based on a search param while typing in input; it is. So, fetching data in effects leads to [race conditions](https://maxrozen.com/race-conditions-fetching-data-react-with-useeffect). You may not see it in development, or even in production, but rest assured that many of your users will surely experience this.
- `useEffect` does not take care of caching, background updates, stale data, etc. which are necessary in apps that are not hobby.
- This requires a lot of boilerplate to write by hand, and hence is not easy to manage and sustain.

Well, does that mean any fetching should not happen in an effect, no:

```jsx
function ProductPage() {
  useEffect(() => {
    // ✅ This logic should be run in an effect, because it runs when page is displayed
    sendAnalytics({
      page: window.location.href,
      event: 'feedback_form',
    })
  }, [])

  useEffect(() => {
    // 🔴 This logic is related to when an event is fired,
    // hence should be placed in an event handler, not in an effect
    if (productDataToBuy) {
      proceedCheckout(productDataToBuy)
    }
  }, [productDataToBuy])

  // ...
}
```

The analytics request made is okay to be kept in `useEffect`, since it will fire when the page is displayed. In Strict Mode, in development in React 18, useEffect will fire twice, but that is fine. ([See here how to deal with that](#twice-in-dev))

In many projects, you can see effects as a way of syncing queries to user inputs:

```jsx
function Results({ query }) {
  const [res, setRes] = useState(null)

  // 🔴 Fetching without cleaning up
  useEffect(() => {
    fetch(`results-endpoint?query=${query}}`).then(setRes)
  }, [query])

  // ...
}
```

Maybe this seems opposite to what we discussed previously: to put fetching logic in an event handler. However, here the query may come from any source(user input, url, etc.) So, the results need to be _`synced`_ with the `query` variable. However, consider the case we discussed before that, the user may press the back button and then forward button; then the data in `res` state variable may be stale or consider the `query` coming from user input and user typing fast. The query might change from `p` to `po` to `pot` to `pota` to `potat` to `potato`. This might initiate different fetches for each of those values, but it is not guaranteed that they will come back in that order. So, the results displayed may be wrong (of any of the previous queries). Hence, cleanup is required here, which ensures that results shown are not stale, and prevents race conditions:

```jsx
function Results({ query }) {
  const [res, setRes] = useState(null)

  // ✅ Fetching with cleaning up
  useEffect(() => {
    let done = false

    fetch(`results-endpoint?query=${query}}`).then(data => {
      if (!done) {
        setRes(data)
      }
    })

    return () => {
      done = true
    }
  }, [query])

  // ...
}
```

This makes sure that only the latest response from all responses is accepted.
Just handling race conditions with effects might seem like a lot of work. However, there is much more to data fetching such as caching, deduping, handling state data, background fetches, etc. Your [framework](https://beta.reactjs.org/learn/start-a-new-react-project#building-with-a-full-featured-framework) might provide an efficient in-built data fetching mechanisms than using `useEffect`.

If you don't want to use a framework, you can extract all the above logic to a custom hook, or might use a library, like [TanStack Query (previously known as useQuery)](https://tanstack.com/query/v4/docs/overview) or [swr](https://swr.vercel.app).

## So Far

- `useEffect` fires twice in development in Strict Mode to point out that there will be bugs in production.
- `useEffect` should be used when a component needs to synchronize with some external system since effects don't fire during [rendering process](https://beta.reactjs.org/learn/render-and-commit) and hence opt out of React's paradigm.
- Don't use an effect for event handlers.
- Don't use effect for derived state. (Heck, don't even use the derived state as long as possible, and calculate values during render).
- Don't use effect for data fetching. If you are in a condition where you absolutely cannot avoid this, at least cleanup at the end of the effect.

## Credits:

Much of the content above is shamelessly inspired from:

- [Beta React Docs](https://beta.reactjs.org/learn/synchronizing-with-effects)
- [Dan Abramov](https://twitter.com/dan_abramov)'s tweets

Liked it? [Checkout my blog](shivamjha.io) for more or [Tweet this article](https://twitter.com/intent/tweet?url=https://dev.to/shivamjjha/useeffect-firing-twice-in-react-18-16cg&text=I+just+read+%22useEffect%20firing%20twice%20in%20React%2018%22+by+%40shivamjjha%0A%0A)