As of recent I’ve been migrating my projects over to use React Hooks. Class components are becoming a thing of a past, an unwieldy and taxing component! So lately I’ve been diving deep, getting into useState and useEffect.

In my capstone project at Flatiron School, one of the biggest issues that I was facing was that of async. My components were loading before the promise was fulfilled and it was a bullet train to error town. It wasn’t until I got into useEffect that I realized such pitfalls can be avoided, by simply using the dependency array!

useState and useEffect, a perfect marriage. If you’re into that sort of thing.

This is a piece of code from my capstone project, and I’m making an API call to grab the data from the backend. We’re setting the call to a variable so that we might use async and await, setting the data to useState, and running the function immediately.

But what’s up with that empty array at the end? Seems… extraneous. However, with a little research I learned that this is the dependency array, and it helps to decide when this should execute.

These are the three situations that you will encounter, and each one handles the dependency array differently.

  1. When a component is rendered for the first time only. In this case, we simply provide an empty array ([]). This is very similar to the lifecycle method componentDidMount().

In my case, seeing that I was running into an async issue, the final option would be the best for my needs. Even if the component initially loads without the fetch data, it will re-render once the data reaches its home. Easy breezy!

These are small but very impactful changes that you can make to your useEffect code to keep things running smoothly. I hope this helps!

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