Member-only story

React 18 and “my useEffects run twice”

Patrick Ullrich
4 min readJun 16, 2022

--

Ever since React 18 has been released I see a lot of confusion around the idea of components mounting twice in strict mode during development. This is important, because it will help you ensure your code is ready for concurrent features. It left a lot of people confused, however; on why their code is “acting weird” and sadly I find most answers pretty lacking, ranging from a confrontational “your code is bad” to a not always helpful web socket example. Sure web sockets are a great example, but most questions I find are around a basic HTTP GET request and no one seems to answer that scenario besides recommending a 3rd party library or not to worry about it because it only happens in development mode. Let’s take a look at the change and shine some light on the new behavior.

What is a useEffect

I will lean heavily on the docs for this section, I believe it just does an outstanding job explaining what effects are and I highly recommend reading it from top to bottom: https://beta.reactjs.org/learn/synchronizing-with-effects

We will focus on specifically this part:

To write an Effect, follow these three steps:

Declare an Effect. By default, your Effect will run after every render.

Specify the Effect dependencies. Most Effects should only re-run when needed rather than after every render. For example, a fade-in animation should only trigger when a component appears. Connecting and disconnecting to a chat room…

--

--

Patrick Ullrich
Patrick Ullrich

Written by Patrick Ullrich

he/him • ReactJS • .NET Core • Software Developer • Rowing • Writing about Software & Life

No responses yet