useEffect firing twice in React 18

Shivam Jha

Shivam Jha / July 30, 2022

11 min read

Gist

Acoording to React 18 Changelog:

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 However, you can stay here and know some of the nuances.

But first, what is an effect?

According to beta react docs:

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.

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

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. You still don't have any need to use an Effect here

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 or performance.now:

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, you should first read this awesome article by Dan Abramov

What is useEffect

useEffect is a react hook 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:

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:

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

  //...
}

So, rule of thumb: 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 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:

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):

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:

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, useEffects 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. 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:

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)

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

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:

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 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) or swr.

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 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: