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.
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.
| Phase | Description | Key Methods Used |
|---|---|---|
| Mounting | Component is created and inserted into the DOM | constructor, componentWillMount, render, componentDidMount |
| Updating | Component’s state or props change, causing re-render | getDerivedStateFromProps, getSnapshotBeforeUpdate, render, componentDidUpdate |
| Unmounting | Component is removed from the DOM | componentWillUnmount |
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}
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.
(1) The lifecycle consists of mounting, updating, and unmounting phases, each with specific methods.
(3) componentWillUnmount is not called during mounting; it is called during unmounting.
| Method | Phase |
|---|---|
| A. componentDidMount | 1. Unmounting |
| B. componentDidUpdate | 2. Mounting |
| C. componentWillUnmount | 3. Updating |
| D. getSnapshotBeforeUpdate | 4. Updating |
A-1, B-3, C-2, D-4.
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.