UseEffect: Endgame

Michael Martinez
2 min readAug 20, 2021

When I first experimented with the UseEffect hook, my program almost instantly broke. My prediction of what would happen was not at all accurate and the code broke from continuous rerendering. It was then that I knew that I needed to dive back into the documentation and really figure out how to correctly use UseEffect.

My initial understanding was that it worked as combination of all the react lifecycle methods: componentDidMount, componentWillUnmount, componentDidUpdate. But one major difference is that there is some cleanup involved, among other things. What useEffect provides is the ability to perform side effects in one’s functional components. These side effects include the fetching of data or changing the DOM of react components.

Setting up subscriptions is another useful side effect. Most commonly, a subscription would be set up in componentDidMount, and then cleaned up in componentWillUnmount. With useEffect however, one may subscribe upon calling useEffect and then clean up by returning a cleanup function. The reason for cleaning up is to prevent performance issues and other bugs. This clean up also happens with every rerender. Performance can be optimized by checking to see if rerendering should occur.

One of the most import aspects of useEffect, is that you can have many useEffects in a single component. Each one is separate and will run its own effect, as well as running in the order that they are declared.

Overall, useEffect is immensely useful. Although it can take a bit of reading and experimenting to truly grasp how useful and powerful these hooks can be, the effort is well worth it, especially with functional components with hooks becoming the preferred component type for modern react. With some practice, useEffect can bring the usefulness of lifecycle methods to all one’s functional components.

--

--