Làm sao để ngăn các Reac...
Làm sao để ngăn các Reac...
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:
React.memo cho Function ComponentsReact.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.
shouldComponentUpdate trong Class ComponentsPhươ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
}
}
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.
senior