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.