DEV Community

Cover image for When useEffect runs
Cassidy Williams
Cassidy Williams

Posted on • Edited on • Originally published at cassidoo.co

139 1 2 1 1

When useEffect runs

useEffect is one of those React/Preact hooks that most people have a love/hate relationship with, but like it or not, it's good to understand how it works. This is not the first blog post on the subject, and it's certainly not going to be the last, but hopefully I can explain some things to you about when (and why!) it runs in your applications for you to use as a reference!

Please tell my friend what useEffect actually is

Your friend asks a good question! First of all, let's talk about side effects in your applications. When I say side effect, I mean it is something that happens when other things are changing.

For example, if I were to have a very simple add function:

function add(x, y) {
    return x + y
}
Enter fullscreen mode Exit fullscreen mode

I could make a side effect of some other variable changing, like so:

let z = 10
function add(x, y) {
    z = z + x // this is the side effect, it does not change the return value
    return x + y
}
Enter fullscreen mode Exit fullscreen mode

Changing that z variable in here does not change the return value of the function, it's just a side effect of adding x and y!

Now in React/Preact, it's a bit more complex, and side effects aren't always a good thing. And useEffect is "usually" for side effects. Developer David Khourshid aptly said that useEffect should probably have been named useSynchronize, because rather than it being, "an extra thing that should happen when state changes happen," it should be more like, "things that happen to stay in sync with certain state changes."

When does useEffect get called?

So, it does get a little hairy because useEffects behavior has changed a bit across framework updates, but at a high level: it's called on component mount, and whenever anything in the dependency array changes. I'll explain this more deeply!

So using this as our base:

useEffect(() => {
  // your fetch call, changes, etc
  return () => {
    // clean-up
  }
}, [dependencyArray]) // we're staying in sync with this
Enter fullscreen mode Exit fullscreen mode

The dependency array

That second parameter of useEffect is called the dependency array. There's 3 things that can happen here:

  • If the dependency array is empty, useEffect is only called once (note: this has changed in React 18 in development and strict mode because of Suspense things, but this is how it is for Preact and pre-React 18 and I will talk about a workaround later in this post)
  • If it doesn't exist (like it's omitted entirely), then useEffect is called on every state change
  • If it has a variable in it, then useEffect is called when that variable changes

If that dependency array is populated, you can think of the useEffect function as staying "in sync" with the variables in the array.

The return function

Whenever useEffect is about to be called again, or whenever the component is about to be dismounted/destroyed, the "clean-up function" is called.

Or to rephrase, React/Preact calls the clean-up functions when a component unmounts, or when an update is made and it needs to "cancel" the previous effect.

As another, more filled out, example:

useEffect(() => {
  let isCurrent = true
  fetchUser(uid).then((user) => {
    if (isCurrent) setUser(user)
  })
  return () => {
    isCurrent = false
  }
}, [uid])
Enter fullscreen mode Exit fullscreen mode

This might look a little confusing, but the way it works is when the component is mounted, the component will fetch the user.

If uid hasn't changed and the component stays mounted, setUser will be called. If uid changes in that time, isCurrent will be set to false, so setUser won't be called for that out-of-date HTTP call.

Stopping useEffect from being called on mount

Besides controlling the dependency array variables, the only other thing you might want to consider is saying, "hey, I don't want this effect to be called on mount, but ONLY on updates in the dependency array." This is weird but it happens.

For this particular case, you'll want to bring in the useRef hook. I'm not going to explain what that hook does here because that deserves its own blog post (this one is pretty good from Robin Wieruch). Let's assume you have some state variable called syncWithMe that you want to stay in sync with:

const hasMounted = useRef(false);

useEffect(() => {
    if (hasMounted.current) {
        // code here only runs when syncWithMe changes!
    } else {
        hasMounted.current = true;
    }
}, [syncWithMe]);
Enter fullscreen mode Exit fullscreen mode

This is called a "ref flag"! In this example, hasMounted acts as an instance variable that doesn't cause re-renders or effect changes (because it isn't a state variable). So, you set it to true when the component mounts, and then whenever syncWithMe changes, the effect function is called.

Having useEffect called only on mount in React 18+

Because of how the new Suspense functionality works and a bunch of other changes that happened in React 18, useEffect needs to be manipulated more to run just once in development and strict mode (it should be fine in production but eh, this is still worth talking about). It'll look a lot like our previous example, but opposite:

const hasMounted = useRef(false);

useEffect(() => {
  if (hasMounted.current) { return; }

  // do something

  hasMounted.current = true;
}, []);
Enter fullscreen mode Exit fullscreen mode

What if I don't want to use useEffect at all?

Then I think you should probably watch or read some thought-leadery content around why it's bad. Heh.

useEffect isn't bad, it just has its own time and place and a lot of people have Opinions™ about how it should be used. I do recommend watching this talk about useEffect in general. It is titled "Goodbye, useEffect" (once again from David Khourshid, who I referenced above), and explains some nuances of when you should and shouldn't use it.

Hopefully this post was useful for you as a reference!

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (14)

Collapse
 
thethirdrace profile image
Comment hidden by post author
Collapse
 
vanyaxk profile image
Ivan

Great article! Why do useEffects trigger when they use callbacks sent as props from the parent? It does not happen with simple callbacks, like the ones from useState though

Collapse
 
tejasq profile image
Tejas Kumar

It’s because the useEffect does a shallow comparison of the values in its dependency array.

Consider the following scenario:

(() => true) === (() => true)
Enter fullscreen mode Exit fullscreen mode

We’re comparing a function that returns true with another function that returns true. We think they’re the same, but to React, they’re two different functions because they’re both initialized as two distinct functions even though they do the same thing.

If we compare references to functions, then we have equality:

const a = () => true;
const b = () => true;
const c = a;

a === a; // true
a === b; // false
a === c; // true
Enter fullscreen mode Exit fullscreen mode

Comparing references, not values achieves the effect you want.

The callbacks from useState are references.

Another way you can go about this is by wrapping your callbacks in useCallback for even more control.

Collapse
 
vanyaxk profile image
Ivan

Thanks a ton, this explains it!

Thread Thread
 
tejasq profile image
Tejas Kumar

Happy to serve you, Ivan!

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Great article. Thank you for sharing.
The useEffect hook is truly a game-changer, it elegantly combines simplicity and functionality, making it an essential tool for any React developer..

Collapse
 
gene profile image
Gene

Thank you!

Collapse
 
bookercodes profile image
Alex Booker

Brilliant explanation @cassidoo. I love the way you write!

Collapse
 
rishadomar profile image
Rishad Omar

Thanks for this articles and the comments below help my understanding.

Collapse
 
lindiwe09 profile image
Doklin

l value the insights and guidance you provide @cassidoo . l love the way you write.

Collapse
 
shiraze profile image
shiraze

Hi, I'm pretty sure the example with let isCurrent = true is incorrect, as isCurrent will be set to true each time the useEffect is fired (after initial render, and whenever uid updates), so will mean that setUser() will be called at each of these times. You could make use of useRef() to make sure it's only called initially, or use the empty dependency array.

Collapse
 
cassidoo profile image
Cassidy Williams

It depends on the fetch timing! If fetch is particularly slow and the uid changes, then the isCurrent will be false for that original fetch call. The functions in useEffect are called in a stack of sorts, with a new isCurrent variable for each one.

Collapse
 
shiraze profile image
shiraze

I thought the fetch promise behaves similar to an enclosure (i.e. the value of inner vars are based on the value of outer vars at the time the function/promise is defined), so I created this codepen to check behaviour: codepen.io/ambience/pen/PodYBqa

You are correct @cassidoo, and we can see from the codepen that if multiple clicks on the button to update uid is made in quick succession, only the last click results in the setUser call being made.

Collapse
 
rei7 profile image
rei

everyone, before you use "ref flag" to bypass react 18+ strict mode running twice, you should know it's actually designed to be a beneficial FEATURE to help catch bugs and find problems. React docs goes to great length talking about it.

Some comments have been hidden by the post's author - find out more

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up