React’s component-based architecture enables us to develop reusable and interactive user interface components. It provides lifecycle methods as part of this system, allowing us to do specified activities at various stages of a component’s existence.
React lifecycle methods
Lifecycle methods are predefined functions that are called at various phases of a React component’s lifecycle. These methods enable us to do specified actions such as initialization, rendering, updating, cleanup, and handling events at various stages of a component’s life cycle, from creation to removal from the DOM.
Each React component has a lifecycle that you can observe and manage through its three major phases. The three phases are:
- Component mounting: birth of your component
- Component updating: growth of your component
- Component unmounting: death of your component
Component mounting
The mounting phase begins when a component is about to be rendered and inserted into the DOM. During this phase, the 3 lifecycle methods are invoked i.e. constructor()
, render()
, componentDidMount()
.
Constuctor()
When a component is formed, constructor()
is the first method that is called. It sets the state of the component and binds event handlers.
Example
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};} // …}
Render()
Render()
method is responsible for rendering the component’s JSX representation onto the screen. It returns the JSX code that describes what should be displayed.
Example
class MyComponent extends React.Component {
render() {
return (
<div>
<h1>Hello, React!</h1>
</div>
);
}
// …
}
ComponentDidMount()
ComponentDidMount()
method is called immediately after the component is mounted in the DOM. It is commonly used for fetching data from APIs or setting up subscriptions.
Example
class MyComponent extends React.Component {
componentDidMount() {
// Fetch data from an API
fetch(‘https://api.example.com/data’)
.then(response => response.json())
.then(data => {
// Update component state with fetched data
this.setState({ data });
});
}
// …
}
Component updating
The updating phase occurs when a component’s state or props change. The lifecycle methods involved in this phase are shouldComponentUpdate()
, render()
,componentDidUpdate()
.
ShouldComponentUpdate()
ShouldComponentUpdate()
method is called before the component is updated, allowing us to optimize performance by determining whether the component should re-render or not. It returns a boolean value.
ComponentDidUpdate()
componentDidUpdate()
method is called immediately after the component is updated in the DOM. It is commonly used for performing side effects or updating the DOM based on new props or states.
class MyComponent extends React.Component {
componentDidUpdate(prevProps, prevState) {
// Perform side effects or update the DOM
if (this.props.isOpen !== prevProps.isOpen) {
// Toggle a modal or update a UI element
// …
}
}
// …
}
Component unmounting
The unmounting phase occurs when a component is about to be removed from the DOM. The lifecycle method involved in this phase is componentWillUnmount()
.
ComponentWillUnmount()
componentWillUnmount()
method is called just before a component is unmounted. It allows us to perform necessary cleanup tasks, such as removing event listeners or canceling subscriptions, to avoid memory leaks.
class MyComponent extends React.Component {
componentWillUnmount() {
// Clean up resources, such as event listeners or subscriptions
window.removeEventListener(‘scroll’, this.handleScroll);
}
// …
}
Explanation
Let’s go through the different stages of the React lifecycle and how they relate to our to-do list application.
Mounting phase
constructor()
: TheTodoApp
component’s constructor is called when the component is initialized. In our application code, we set the initial state,tasks
, to an empty array.render()
: Therender()
method is responsible for rendering the JSX representation of the component. It returns the HTML elements, including theTodoForm
andTodoList
components, along with the current list of tasks.componentDidMount()
: This lifecycle method is invoked after the component is inserted into the DOM. In this case, we don’t have any specific action to perform, so we don’t include it in our example.
Updating phase
shouldComponentUpdate()
: This method is not explicitly defined in our example. React automatically performs a shallow comparison of state and props to determine if the component needs to re-render. If any changes occur, the component will update.render()
: Therender()
method is invoked again when the component is updated, reflecting any changes in the state. It re-renders theTodoForm
andTodoList
components with the updated list of tasks.componentDidUpdate()
: We don’t use this method in our example. It is typically used for performing side effects after a component update, such as making additional API calls or interacting with the DOM.
Unmounting phase
componentWillUnmount()
: Since our application doesn’t have a specific component unmounting event, we don’t include this method in our example. It is commonly used to clean up resources like event listeners or subscriptions before the component is removed from the DOM.