Lifecycle of Components In React.

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: 

  1. Component mounting: birth of your component
  2. Component updating: growth of your component
  3. 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(): The TodoApp 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(): The render() method is responsible for rendering the JSX representation of the component. It returns the HTML elements, including the TodoForm and TodoList 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(): The render() method is invoked again when the component is updated, reflecting any changes in the state. It re-renders the TodoForm and TodoList 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.

Related Posts

What are custom events in JavaScript?

Custom events are the events that allow you to decouple the code you want to run after a specific piece of code runs. There are various in-built events…

How to use nested for loop in JavaScript?

We use the for loop statement of JavaScript for repeating a set of statements inside the loop body a specified number of times. A nested for loop, as the…

What are the basic rules for JavaScript parameters?

A JavaScript function is a code that performs a particular task. The function parameters are the name list in the function definition. Parameters are also known as…

How to stop refreshing the page on submit in JavaScript?

Using event.preventDefault() to stop page refresh on form submit In this section, we will see how to use event.preventDefault() to stop page refresh on form submission. The event.preventDefault() restricts the default…

Target a Window Using JavaScript or HTML

TARGET attribute of HTML A link’s opening named frame or window is specified using the Target attribute of the <a> anchor tag. The concluding </a> tag in…

What is the role of deferred scripts in JavaScript?

Since JavaScript is a loosely typed language, you are not required to correctly predict the kind of data that will be kept in a variable. Depending on the information…