Comparing useEffect Hooks with Life Cycle Methods
After seeing how we can be more precise in our code using effects compared to life cycles, let's have a brief overview, through a diagram, to see how the life cycle methods in the class components work, as shown in the following:
In classes, you have life cycle methods that tap into some state of that component. The problem with that model is that you may actually need to break each event into multiple different unrelated functions. For example, say you want to attach an event listener and, to avoid memory leaks, you want to remove the listener when it is no longer needed. What you must do in a class-based component is to attach it in componentDidMount
and remove it in componentWillUnmount
. This means that, now, both of those life cycle methods must track and have access to that listener. Instead of our code being grouped by context, it is grouped by life cycle methods...