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!
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.
- 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().
- When the component is rendered for the first time, and whenever it re-renders. In this case, we don’t provide an array at all! Be careful with this, as a common issue is falling into an infinite loop. Never to return.
- When the component is rendered for the first time and whenever it re-renders as well as some piece of data has changed. In this case, we need to provide pieces of data that have changed since the initial render. In the example above, I would be able to put “posts” inside the array as [posts]. Now, useEffect will run on the initial render, as well as any time the data living with “posts” has changed.
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!