Why components need a lifecycle
React components go through a lifecycle, whether our code knows about it or not. In fact, the render()
method that you've implemented in your components so far in this book, is actually a lifecycle method. Rendering is just one lifecycle event in a React component.
For example, there's lifecycle events for when the component is about to be mounted into the DOM, for after the component has been mounted to the DOM, when the component is updated, and so on. Lifecycle events are yet another moving part, so you'll want to keep them to a minimum. As you'll learn in this chapter, some components do need to respond to lifecycle events to perform initialization, render heuristics, or clean up after the component when it's unmounted from the DOM.
The following diagram gives you an idea of how a component flows through its lifecycle, calling the corresponding methods in turn:
These are the two main lifecycle flows of a React component. The first...