Welcome 🎉

logo

ReactLMS

Search
Light Mode
Contact Us

2 min to read

Contact us

No results for your search.
Sorry, an unexpected error occurred

Concept


LifeCycle is the life cycle of a component

LifeCycle helps us:


Cycle of operation


LifeCycle is divided into 3 stages:


Mounting


The cycle will be executed when the component is integrated into the DOM

Constructor will be executed at the beginning of the cycle

ComponentDidMount will be executed when the cycle ends, it is the place to call API.


Updating


The cycle will be executed when the component is being updated.

The cycle will be activated when:

ComponentDidUpdate will be executed when the cycle ends, usually used to handle logic when data changes.


Unmounting


The cycle will be executed when the component is removed from the DOM

ComponentWillUnmount will be executed when the lifecycle ends, usually used to cancel unnecessary tasks such as canceling subscriptions, removing event listeners, etc.


Example


import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
    };
  }

  componentDidMount() {
    // Gọi API để lấy dữ liệu sau khi component được render lần đầu tiên
    // và cập nhật state của component
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => this.setState({ data }))
      .catch(error => console.log(error));
  }

  componentDidUpdate(prevProps, prevState) {
    // Xử lý logic khi state hoặc props thay đổi
    if (prevState.data !== this.state.data) {
      console.log('Data has been updated');
    }
  }

  componentWillUnmount() {
    // Hủy các tác vụ không cần thiết trước khi component bị xoá khỏi DOM
    // Như hủy các subscription, định bịnh các event listener, v.v.
  }

  render() {
    return (
      <div>
        {/* Hiển thị dữ liệu */}
        {this.state.data.map(item => (
          <p key={item.id}>{item.name}</p>
        ))}
      </div>
    );
  }
}

export default MyComponent;








Read more
On This Page