Hi 🤓 Cảm ơn bạn đã ghé thăm blog này, nếu những bài viết trên blog giúp ích cho bạn. Bạn có thể giúp blog hiển thị quảng cáo bằng cách tạm ngừng ad blocker 😫 và để giúp blog duy trì hoạt động nếu bạn muốn.
Cảm ơn bạn!

Trong bài viết này, chúng ta cùng tìm hiểu về React.Component vs React.PureComponent và xem chúng có điểm gì khác nhau nhé.

Như các bạn đã biết, mỗi khi props hay state của một component thay đổi, component này sẽ re-render và kéo theo các child component khác re-render. Và trong React lifecycle có một method gọi là shouldComponentUpdate(), method này nhằm giúp chúng ta xử lý re-render của component bằng cách so sánh propsstate hiện tại với next props, next state, nếu thay đổi một trong 2 thì component sẽ thực hiện re-render.

Method shouldComponentUpdate() có liên quan gì đến React.ComponentReact.PureComponent? Thực ra đây chính là điểm khác biệt chính giữa React.Component vs React.PureComponent.

React.Component

Đối với class component khi sử dụng React.Component ta chỉ cần extends nó.

class User extends React.Component {
  render() {
    return <h1>My name is Ha<h1>
  }
}

Thông thường khi chúng ta sử dụng React.Component, React sẽ thực hiện re-render mỗi khi props hay state của component thay đổi, lý do là vì method shouldComponentUpdate() trong trường hợp này mặc định return true, điều đó cho phép component re-render.

Nếu parent component re-render mà child component sử dụng React.Component, thì nó sẽ không thực hiện so sánh props, state mà sẽ re-render kể cả khi propsstate không thay đổi.

React.PureComponent

Khi sử dụng React.PureComponent, method này có thể giúp chúng ta cải thiện hiện suất cho trang web, lý do là vì nó sử dụng method shouldComponentUpdate() để so sánh current props , current state với next propscurrent state. Nếu propsstate không thay đổi thì component sẽ không re-render 😁.

class User extends React.PureComponent {
  render() {
    return <h1>My name is Ha<h1>
  }
}

Khi so sánh thì PureComponent sẽ sử dụng shallow compare để so sánh nextProps với this.props, nextState với this.state. Mình đã có một bài viết liên quan đến shallow compare, các bạn có thể đọc tại đây: Shallow Compare trong React là gì?.

Tóm lại điểm khác biệt giữa React.PureComponentReact.ComponentReact.PureComponent sẽ thực hiện so sánh props, state và quyết định xem có re-render component hay không, còn React.Component sẽ re-render kể cả khi component này có propsstate không đổi ^^.

Có thể bạn thích ⚡
homiedev
About Me

Hi, I'm @devnav. Một người thích chia sẻ kiến thức, đặc biệt là về Frontend 🚀. Trang web này được tạo ra nhằm giúp các bạn học Frontend hiệu quả hơn 🎉😄.

Chúc các bạn tìm được kiến thức hữu ích trong blog này 😁😁.