Câu hỏi

Làm sao để ngăn các React component re-render?

Câu trả lời

Trong React, việc ngăn chặn các component không cần thiết phải re-render có thể giúp tối ưu hóa hiệu suất ứng dụng. Dưới đây là một số cách để ngăn chặn re-render:

Sử dụng React.memo cho Function Components

React.memo là một higher order component (HOC) mà nó chỉ cho phép component re-render khi props của nó thay đổi.

const MyComponent = React.memo(function MyComponent(props) {
  /* render using props */
});

Khi props không thay đổi, MyComponent sẽ không re-render.

Sử dụng shouldComponentUpdate trong Class Components

Phương thức shouldComponentUpdate cho phép bạn quyết định xem một component có nên cập nhật hay không dựa trên sự thay đổi của props hoặc state.

class MyComponent extends React.Component {
  shouldComponentUpdate(nextProps, nextState) {
    // return true nếu component cần cập nhật
    // return false nếu không
  }
}

Sử dụng PureComponent

React.PureComponent giống như React.Component nhưng nó thêm một shouldComponentUpdate() với một shallow prop và state comparison.

class MyComponent extends React.PureComponent {
  // ...
}

Nếu props hoặc state của component không thay đổi, component sẽ không re-render.

S...

Bạn cần đăng nhập để xem
senior

senior

Gợi ý câu hỏi phỏng vấn

senior

Làm thế nào để sử dụng Polymer trong React?

middle

Life Cycle trong React hoạt động như thế nào?

middle

Children prop trong React là gì?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào