Each React component has a lifecycle that you can monitor and manage across its three main phases: Mounting, Updating, and Unmounting.
Mounting refers to the process of inserting elements into the DOM. React has four built-in methods that are called in the following order during component mounting:
constructor()
getDerivedStateFromProps()
render()
componentDidMount()
The render()
method is mandatory and will always be called, while the others are optional and will be invoked if you define them.
The constructor() method is called first when the component is initialized and is the ideal place to set up the initial state and other values. It receives props as arguments, and you should always begin by calling super(props) to invoke the parent’s constructor, which enables the component to inherit methods from its parent (React.Component).
The constructor
method is called by React each time a component is created.
class |
The getDerivedStateFromProps()
method is called just before rendering the element(s) to the DOM. It is the appropriate place to update the state based on the initial props. This method takes props
and state
as arguments and returns an object with the updated state. In the example below, the favorite color starts as “red,” but getDerivedStateFromProps()
updates it according to the favcol
attribute.
The getDerivedStateFromProps method is called immediately before the render method.
class |
The render() method is required and is responsible for generating the HTML that is output to the DOM.
A basic component with a straightforward render()
method:
class const |
The componentDidMount() method is called after the component has been rendered. This is where you execute statements that depend on the component being placed in the DOM.
Initially, my favorite color is red, but just wait a moment, and it will change to yellow.
class |