How to Fix the Infinite Loop Inside “useEffect” (React Hooks)

Andrew Myint
3 min readJul 24, 2019
Photo by Bundo Kim on Unsplash

If you start using React-Hooks, your component might need a life cycle method at some point. And that is when you start using useEffect() (a.k.a. the Effect Hook). Then boom! You have encountered an infinite loop behavior, and you have no idea why the hell that is. If that happens, this article will explain why and how you can prevent it.

Example Using Effect Hook

The code snippet below is an example of using Effect Hook, but it has an infinite loop behavior.

A problem snippet code for causing an infinite behavior

What does this code do?

  • In a nutshell, the component “DisplayName” has two states, which are “name” and “userId”.
  • And it has a function called “fetchUser()” which handles fetching data from the API and setting the “name”.
  • Then, there is "useEffect(),which will call “fetchUser()” after rendering a DOM element.

Where is the problem?

  • The “useEffect()”, will run after the initial render, then invoke the “fetchUser()”.
  • Inside “fetchUser”, it will update the state “name” on line 9. Then it will trigger the component to re-render again.
  • As a result, “useEffect()” will run again and update the state. Next, the whole process repeats again, and you're trapped inside an infinite loop.
The diagram of Infinite loop behavior

The Solution for Infinite Behavior

A solution snippet code for an infinite behavior

“You can tell React to skip applying an effect if certain values haven’t changed between re-renders. To do so, pass an array as an optional second argument to useEffect”, from the official documentation.

In the snippet above, we now have an optional second argument [userId] passed in “useEffect()”.

By providing [userId] as a second argument, we are just telling “useEffect()” to run only if a certain value (userId) has changed between the component re-renders.

Here below, I’ve provided a simple diagram for the sake of simplicity.

The diagram of skipping useEffect

And now, we’ve escaped from the infinite world! If you want to explore more about the useEffect hook, here is a complete guide for using useEffect by Dan Abramov. It is a very good article with a clear explanation.

Thanks for your time. See you soon.

--

--

Andrew Myint

JavaScript | React | Software Engineer| Effective learning is by teaching and sharing with others.