useEffect Hook — Loop de Loop

Are you transitioning form class components to functional in React? Let me guess, you’re having trouble using the useEffect and getting stuck in a loop. Don’t worry, you are not alone in this. I also had a bit of trouble understanding its nuances so I dug a little deeper.

The useEffect hook is used when data fetching, setting up a subscription, and manually changing the DOM in React components. If you’re familiar with class components, this hook can be configured to act like lifecycle methods. We use the hook to mimic a componentDidMount(), componentDidUpdate(), and componentWillUnmount() but they aren’t exactly a one to one substitute. In this post I will focus on utilizing the hook to fetch data and mount my component since it is the first hurdle I encountered when using it.

Example

As you can see, we’ve got a functional component called DisplayName utilizing two hooks. The two pieces of state, name and userId are set using the useState hook. We then have a fetchUser() function which handles fetching data from an API and setting the state using the setName() setter function. Then, we have our useEffect function which will call the fetchUser function after rendering the DOM element.

The Problem

Solution