Greetings friends, gather ‘round, and let me tell you a tale of woe about useEffect. This will be a quick one, I promise.

First, a little background…

Since my graduation at Flatiron, I’ve been working a lot with ReactJs. It’s my jam, and its become even moreso with the advent of Hooks. With the formatting of useState and useEffect, and perhaps some in-component styling, I’ve found it to be my home.

However, there has been one thing that has been plaguing me, and it falls onto the shoulders of useEffect. You foul mistress. What could cause such turmoil and vitriol to an otherwise optimistic person?

The dreaded dependency array.

All the colors of the rainbow

What I’d like to draw your attention to is example 3, where I have “dependency” listed in the array brackets. The purpose of this is you’re able to add, say a piece of state to this array, and if the information in that state changes, the component will re-render to reflect it.

However, what has been plaguing me on several projects has been that the moment I add a dependency, my program flips out and starts running ad infinitum. The dreaded infinite loop strikes again. But why?

Photo by Noah Buscher on Unsplash

It turns out that useEffect has a pesky little bug living in it! And it rears its ugly head when you attempt to pass an array INTO this dependency array. My logic was simple, implement useEffect to make an API call to populate data, save it state, and re-render the component. As it turns out, a slight modification can fix this snafu. Within your dependency array, instead of providing the array itself, provide the length! Instead of filling in those brackets with “dependency” fill it in with “dependency.length”.

This will cause your app to re-render once the promise is returned and set to state. Presto chango, no more infinite loop!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store