...
/The Role of Lifecycle Methods in Combination with Components
The Role of Lifecycle Methods in Combination with Components
Interact with different lifecycle methods and learn about each of them in detail.
We'll cover the following...
In the beginning, we mentioned a few other lifecycle methods apart from componentDidMount()
and componentWillMount()
. React also recognizes these if they have been implemented
within a class component.
To understand these different lifecycle methods better, let’s create an example component in which we include the lifecycle methods in debug messages. This will help us to see them in the browser console. To be more precise, the example actually consists of two components:
- Parent component
- Child component, which receives props from its parent component (which it simply ignores in this case).
import React from 'react'; import ReactDOM from 'react-dom'; import ParentComponent from './app.js'; require('./style.css'); ReactDOM.render( <ParentComponent />, document.getElementById('root') );
Both of these components reliably lead to the following result:
Note: You can visualize console output by navigating to the console tab of inspect element in the browser.
Wow! A lot is happening here. Let’s go through this one by one, starting with the mounting phase.
constructor(props)
The first method to be called is the constructor
of the ParentComponent
component. React processes components in the tree from the outside to the inside. In other words, the further up the component is in the component hierarchy, the earlier it will be instantiated.
Afterwards, its render()
method is called. This is necessary because otherwise React would not know which child components actually need to be processed and included in the component tree. React only runs the lifecycle methods for those components that have actually been included in the render()
method of their parent component.
The constructor is passed the props of the component as a parameter and can transmit them to its parent component (mostly React.Component
or React.PureComponent
) with super(props)
. If omitted, this.props
in the constructor would be undefined, leading to unexpected bugs and behavior.
Note: In most cases today, it is not necessary to declare the constructor. The Babel plugin class properties can be used instead to implement instance methods as well as state as their own class properties. If the class properties are not used, the constructor is the place to define the initial state (for example
this.state = { }
) and bind the instance methods to their respective class instances with.bind()
(for examplethis.handleClick = this.handleClick.bind(this)
). This is necessary as instance methods would otherwise lose their context within the component as their event listeners are used inside JSX, andthis
would not point to the instance of the component anymore. ...