Câu hỏi phỏng vấn React.js
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...

senior

senior

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

middle

Làm thế nào để có thể tạo ref trong React?

middle

Bạn thích hooks nào trong React? Hãy mô tả cách tạo một hooks bất kỳ.

middle

Error Boundary được xử lý thế nào trong React?

Bình luận

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

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