Why you should avoid useEffect

Thales Kenne
3 min readMay 2, 2021

Disclaimer: I’m not saying useEffect is bad. It is a very helpful tool that helps you “watch” over variables and run side effects. The are several use cases where you’ll want to use useEffect, but they are often the exception, not the rule. Make sure you understand where and when to use it.

If you read the disclaimer, you might have noticed I put “side effects” in bold. This is exactly what this article is about. If used incorrectly, useEffect makes for very poor code with little readability. Usually when writing code, you’re looking to make it straightforward and easy to read. You want a linear code, if you know what I mean. A calls B, which in turn calls C.

That makes it easy for a developer to understand what is happening. But what happens if in between “A calls B”, we have a “A calls (useEffect calls D) B” ? This is exactly what useEffect could potentially do to your code.

Suddenly it feels like you’re reading the script from Dark. You’re going back and forth in time. I mean, lines.

Let’s build a quick example. Let’s say we’re building an application that searches which party a president’s runs for:

In the example above, the user types in the input, which changes the input value. We then have a useEffect that listens to changes in the presidentName variable, that then triggers the API to fetch results.

Notice that to read the code we need to understand the entire file?

Now, let’s get to the point. Take a look what Redux’s creator, Dan Abramov, says about this topic:

In other words, if you’re using a side effect to perform some action which was triggered by the user, you’re messing up your code. It’s no longer linear. In our example, the user typed in the input, which should call our api straight in the event handler.

Let’s refactor our code to follow this rule:

Now, notice that the code got much simpler. We no longer need the useEffect and a new developer coming into our code can understand straight away where every change is coming from.

Rule of thumb: If you have an event ( button click, input change, etc…) make it trigger all the “side effects” you need.

Now that we’ve cleared that up, it’s time to get back to the code editor ;)

--

--

Thales Kenne

I'm a web and mobile developer who believes in learning by teaching