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.
Take a look at the code below.
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 useEffect() hook runs every time the component renders. This means that our function fetchUser will execute which will “setName()” state to whatever the response is. The problem with this is that a React component always re renders when its state changes so it will loop back over running the useEffect hook in an infinite loop.
The solution to this problem lies int the second argument of the useEffect function. As we know the first is a function while the second is our dependency. This means that if anything within the second argument changes the useEffect function will only then be triggered. In our case, the userId piece of state is passed in to UseEffect as the dependency. Now, our useEffect will only run if the userId is changed which will get us out of our infinite loop. If you wish to dive in deeper into the useEffect hook, the documentation is a great start. I also recommend watching some YouTube videos and practicing along to really solidify your understanding.