What are Lifecycle Methods?
A 5-yr old guide to understanding lifecycle methods.
Click to read for free — if blocked behind the Medium paywall.
He’s been writing software for a while, but new to the React ecosystem.
For a long time he didn’t fully understand what lifecycle truly meant in the context of React apps.
When you think of lifecycle what comes to mind?
What’s Lifecycle Anyway?
Well, consider humans.
The typical lifecycle for a human is something like, “child” to “adult” to “elderly”.
In the biological sense, lifecycle refers to the series of “changes in form” an organism undergoes.
The same applies to React components. They undergo a series of “changes in form”.
Below’s what a simple graphical representation for React components would be like.
The four essential phases or lifecycle attributed to a React component include:
- Mounting — like the birth of a child, at this phase the component is created (your code, and react’s internals) then inserted into the DOM
- Updating — like humans “grow”, in this phase a React component undergoes growth by being updated via changes in props or state.
- Unmounting — Like the death of a human, this is the phase the component is removed from the DOM.
- Error Handling — Think of this as being comparable to when humans fall sick and visit the doctor. Sometimes your code doesn’t run or there’s a bug somewhere. When this happens, the component is in the error handling phase. I intentionally skipped this phase in the illustration earlier.
Now that you understand what lifecycle means, what are lifecycle methods?
Knowing the phases / lifecycle a React component goes through is one part of the equation. The other part is understanding the methods React makes available (or invokes) during each phase.
With humans, there are specific qualities associated with each lifecycle phase.
For example, a child could cry all day, an adult is typically bigger and stronger than a child, and the elderly are usually full of experience.
In the same vein, React lifecycle phases have associated methods to them. In some cases the methods are unique to only a particular phase, in others, a method could be associated to more than one lifecycle phase.
The methods invoked during the different phases/lifecycle of a React component is what’s popularly known as the component lifecycle methods e.g. In the mounting and updating phases, the
render lifecycle method is always invoked.
Consequently, there are different lifecycle methods available on all 4 phases of a React component i.e the mounting, updating, unmounting and error handling phases.
Knowing when a lifecycle method is invoked (i.e the associated lifecycle/phase) means you can go ahead to write related logic within the method and know it’ll be invoked at the right time.
For a more deep dive on lifecycle methods, you may read my somewhat longer article on the same subject.
For deeper studies, get my book, Reintroducing React — learn modern React from scratch.