ReactJS Cơ bản

Component trong ReactJS

Component trong ReactJS

Trong ReactJS, có hai loại component chính là Stateful Component và Stateless Component.

1. Stateful Component (còn gọi là Class Component):

Là component có trạng thái (state) và có thể thay đổi trạng thái của nó. Stateful component được tạo bằng class và kế thừa từ React.Component hoặc React.PureComponent.

Chúng ta sử dụng Stateful Component khi cần quản lý trạng thái hoặc xử lý logic phức tạp hơn.

Ví dụ:

import React, { Component } from 'react';

class StatefulComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      <div>
        <h2>{this.state.count}</h2>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}

export default StatefulComponent;

2. Stateless Component (còn gọi là Function Component):

Là component không có trạng thái và chỉ đơn giản là một hàm trả về giao diện.

Stateless component được tạo bằng function. Chúng ta sử dụng Stateless Component khi chỉ cần render giao diện tĩnh hoặc không cần quản lý trạng thái hoặc xử lý sự kiện.

Ví dụ:

import React from 'react';

const StatelessComponent = (props) => {
  return (
    <div>
      <h2>{props.name}</h2>
    </div>
  );
};

export default StatelessComponent;

Theo mình nếu bạn cần quản lý trạng thái hoặc xử lý logic phức tạp, sử dụng Stateful Component; nếu chỉ cần render giao diện, sử dụng Stateless Component.


Chia sẻ bài viết:
Bình luận trực tiếp trên web
Bài viết liên quan
Props trong ReactJs

Props trong ReactJs

Props là một tính năng trong React cho phép component cha truyền dữ liệu cho component con.

11-02-2023 · ReactJS Cơ bản · 1 phút đọc · 1010
Props Validation trong ReactJS

Props Validation trong ReactJS

Props Validation trong ReactJS là một cách để kiểm tra rằng component con nhận được các props chính xác theo yêu cầu.

11-02-2023 · ReactJS Cơ bản · 3 phút đọc · 994
Các API thường dùng trong React Components

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...

11-02-2023 · ReactJS Cơ bản · 2 phút đọc · 957
State trong ReactJS

State trong ReactJS

State là một tính năng trong React cho phép component quản lý trạng thái của chính nó. Trạng thái là một đối tượng lưu trữ dữ liệu tạm thời của component.

11-02-2023 · ReactJS Cơ bản · 2 phút đọc · 1020