Mark As Completed Discussion

Lifecycle Methods in React

Lifecycle methods are special methods that are automatically called by React at specific points during the life cycle of a component. These methods can be used to perform actions at different stages of the component's life cycle, such as when it is created, updated, or destroyed.

In class components, some common lifecycle methods include:

  • constructor(): This method is called when a component is first created. It is used to initialize the component's state and bind event handlers.

  • componentDidMount(): This method is called after the component has been rendered to the DOM. It is often used to fetch data from an API or set up event listeners.

  • componentDidUpdate(prevProps, prevState): This method is called after a component has been updated. It receives the previous props and state as arguments, allowing you to compare the current and previous values and perform any necessary actions.

  • componentWillUnmount(): This method is called just before a component is removed from the DOM. It is used to clean up any resources or event listeners created in the componentDidMount() method.

Here's an example of a class component with lifecycle methods:

SNIPPET
1import React, { Component } from 'react';
2
3class Counter extends Component {
4  constructor(props) {
5    super(props);
6    this.state = {
7      count: 0
8    };
9  }
10
11  componentDidMount() {
12    console.log('Component mounted');
13  }
14
15  componentDidUpdate(prevProps, prevState) {
16    if (prevState.count !== this.state.count) {
17      console.log('Count updated');
18    }
19  }
20
21  componentWillUnmount() {
22    console.log('Component unmounted');
23  }
24
25  incrementCount() {
26    this.setState(prevState => ({ count: prevState.count + 1 }));
27  }
28
29  render() {
30    return (
31      <div>
32        <h2>Counter: {this.state.count}</h2>
33        <button onClick={() => this.incrementCount()}>Increment</button>
34      </div>
35    );
36  }
37}
38
39export default Counter;
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment