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

Andrew Myint
Jul 24 · 3 min read

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

Example Using Effect Hook

The code snippet below is the example of using Effect Hook, but it has an infinite loop 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 handle fetching data from API and set the “name”.
  • Then, there is“useEffect()” which will call the “fetchUser()” after rendering a DOM element.

Where is the problem?

  • The “useEffect()”, will run after the initial render, then invoke the “fetchUser()”.
  • Inside the “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 Solution for 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 the “useEffect()”.

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

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

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

Thanks for your time, see you soon.

Andrew Myint

Written by

JavaScript | React | Full Stack Developer | The Effective learning is by teaching and sharing to the others.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade