# Các API thường dùng trong React Components

> Các API thường dùng trong React như render, constructor, componentDidMount, shouldComponentUpdate, componentDidUpdate, componentWillUnmount...

- URL: https://vietanhjs.com/cac-api-thuong-dung-trong-react-components.html
- Chuyên mục: [ReactJS Cơ bản](https://vietanhjs.com/reactjs-co-ban)
- Tác giả: [Hoàng Văn Việt Anh](https://hoangvanvietanh.com/)
- Xuất bản: 2023-02-11T17:22:41+07:00

---

1. `render`: Là hàm chính để render các element của component.
2. `constructor`: Là hàm khởi tạo khi một component được tạo ra.
3. `componentDidMount`: Là một lifecycle method được gọi sau khi component đã được mount.
4. `shouldComponentUpdate`: Là một lifecycle method được gọi trước khi một component được render lại.
5. `componentDidUpdate`: Là một lifecycle method được gọi sau khi component đã được render lại.
6. `componentWillUnmount`: Là một lifecycle method được gọi trước khi component được unmount.
7. `setState`: Là hàm để cập nhật trạng thái (state) của component.
8. `forceUpdate`: Là hàm để yêu cầu component render lại, mặc dù hàm `shouldComponentUpdate` trả về false.
9. `props`: Là object chứa tất cả các thuộc tính (props) truyền vào component từ component cha.
10. `state`: Là object chứa trạng thái của component.
11. `defaultProps`: Là object chứa các giá trị mặc định cho các thuộc tính (props) của component.
12. `context`: Là object chứa các giá trị được truyền xuống từ component cha tới tất cả các component con.
13. `ref`: Là một tham chiếu đến element DOM hoặc instance của component đang được render.

Ví dụ:

```

import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props, context) {
    super(props);
    this.state = {
      message: 'Hello World!'
    };
    this.myRef = React.createRef();
    this.context = context;
  }

  componentDidMount() {
    console.log('My component has been mounted');
    console.log('Context: ', this.context);
  }

  componentWillUnmount() {
    console.log('My component will be unmounted');
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.state.message !== nextState.message) {
      return true;
    }
    return false;
  }

  componentDidUpdate(prevProps, prevState) {
    console.log('My component has been updated');
  }

  handleClick = () => {
    this.setState({
      message: 'Hello React!'
    });
  };

  handleForceUpdate = () => {
    this.forceUpdate();
  };

  render() {
    return (
      <div ref={this.myRef}>
        <h1>{this.state.message}</h1>
        <button onClick={this.handleClick}>Update State</button>
        <button onClick={this.handleForceUpdate}>Force Update</button>
      </div>
    );
  }
}

MyComponent.contextType = {
  theme: PropTypes.string
};

export default MyComponent;
```

Ngoài các API trên là các API thường được sử dụng nhiều nhất thì React còn nhiều loại API chúng ta sẽ tìm hiểu sau nhé.
