Browse Courses

Components Lifecycle

This document explains the lifecycle of React class components, detailing the mounting, updating, and unmounting phases, and the lifecycle methods used in each phase.

This document explores the lifecycle of React class components, covering the mounting, updating, and unmounting phases, and the key lifecycle methods available in each phase. It explains how these methods interact with the DOM and how developers can use them to control component behavior.


Introduction to Component Lifecycle

React class components have a lifecycle, meaning they go through distinct phases during their existence. The lifecycle consists of three main phases: mounting, updating, and unmounting. Each phase provides specific lifecycle methods that allow developers to control and respond to changes in the component’s relationship with the DOM.


Lifecycle Phases and Methods

PhaseDescriptionKey Methods Used
MountingComponent is created and inserted into the DOMconstructor, componentWillMount, render, componentDidMount
UpdatingComponent’s state or props change, causing re-rendergetDerivedStateFromProps, getSnapshotBeforeUpdate, render, componentDidUpdate
UnmountingComponent is removed from the DOMcomponentWillUnmount

Mounting Phase

  • constructor: Initializes the component and sets up initial state.
  • componentWillMount: Invoked before the first render (legacy, rarely used in modern React).
  • render: Returns the JSX to display in the UI.
  • componentDidMount: Called after the component is mounted; used for side effects like data fetching.

Updating Phase

  • getDerivedStateFromProps: Syncs state with updated props before rendering.
  • getSnapshotBeforeUpdate: Captures information from the DOM before it changes.
  • render: Updates the UI based on new state or props.
  • componentDidUpdate: Runs after the component updates; used for side effects or further state changes.

Unmounting Phase

  • componentWillUnmount: Called before the component is removed from the DOM; used for cleanup like canceling network requests or removing event listeners.

Example: Lifecycle Methods in a Class Component

 1class DemoComponent extends React.Component {
 2  constructor(props) {
 3    super(props)
 4    this.state = { count: 0 }
 5  }
 6
 7  componentDidMount() {
 8    // Called after mounting
 9    console.log('Component mounted')
10  }
11
12  componentDidUpdate(prevProps, prevState) {
13    // Called after updating
14    if (prevState.count !== this.state.count) {
15      console.log('Count updated')
16    }
17  }
18
19  componentWillUnmount() {
20    // Called before unmounting
21    console.log('Component will unmount')
22  }
23
24  render() {
25    return (
26      <div>
27        <p>Count: {this.state.count}</p>
28        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
29          Increment
30        </button>
31      </div>
32    )
33  }
34}

Key Points

  • The component lifecycle manages the relationship between a component and the DOM.
  • Lifecycle methods allow developers to run code at specific points in a component’s existence.
  • Proper use of lifecycle methods enables side effects, data fetching, cleanup, and more.

Conclusion

Understanding the component lifecycle is essential for building robust React applications. By leveraging lifecycle methods, developers can control initialization, updates, and cleanup, ensuring components behave predictably and efficiently.


FAQ

  1. The lifecycle consists of mounting, updating, and unmounting phases, each with specific methods.
  2. The lifecycle only includes rendering the component once.
  3. The lifecycle is only about handling user events.
  4. The lifecycle is managed entirely by the browser.
(1) The lifecycle consists of mounting, updating, and unmounting phases, each with specific methods.

The component may leave behind event listeners or network requests, leading to memory leaks or unexpected behavior after it is removed from the DOM.

  1. The constructor initializes the component and state.
  2. componentDidMount is called after the first render.
  3. componentWillUnmount is called during mounting.
  4. The render method returns the JSX for the UI.
(3) componentWillUnmount is not called during mounting; it is called during unmounting.

getDerivedStateFromProps syncs state with updated props before rendering, while getSnapshotBeforeUpdate captures information from the DOM before it changes.

The render method is called in both the mounting and updating phases to generate the UI based on current state and props.

MethodPhase
A. componentDidMount1. Unmounting
B. componentDidUpdate2. Mounting
C. componentWillUnmount3. Updating
D. getSnapshotBeforeUpdate4. Updating
A-1, B-3, C-2, D-4.

Understanding the lifecycle allows developers to control initialization, updates, and cleanup, ensuring components behave predictably and efficiently.

Methods like componentDidMount and componentDidUpdate can be used for data fetching, subscriptions, or triggering actions after rendering.

Ensure that the correct lifecycle methods are implemented and that state or props are being updated properly.

The componentWillUnmount method is called before a component is removed from the DOM, allowing for cleanup operations.

True. componentWillUnmount is used for cleanup before the component is unmounted.