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.