首頁 > web前端 > js教程 > 主體

優化 React 中的重新渲染:最佳實踐

Mary-Kate Olsen
發布: 2024-09-20 06:43:32
原創
619 人瀏覽過

Optimizing Re-Rendering in React: Best Practices

React 效能瓶頸的主要原因之一是重新渲染,尤其是在大型應用程式中。 React 的虛擬 DOM 機制有效地更新了 DOM,但不必要的重新渲染仍然會導致效能問題。可以優化重新渲染,以確保只有需要重新渲染的元件,從而提高應用程式效能和回應能力。

本文將討論減少 React 應用程式中無意義重新渲染的最佳實踐,以及一些有用的提示和方法來幫助您最大限度地提高 React 元件的效率。

了解 React 中的重新渲染

React 的渲染過程圍繞著其元件樹展開。當元件的狀態或屬性改變時,React 會重新渲染該元件及其子元件。但是,如果管理不當,這可能會導致不必要的重新渲染,未經歷任何實際變更的元件也會重新渲染,從而浪費資源。

不必要的重新渲染的常見原因

不影響組件輸出的道具或狀態變更。
父元件重新渲染會導致子元件重新渲染,即使它們的 props 沒有改變。
每次渲染時都會重新建立匿名函數或物件參考。

React 中最佳化重新渲染的關鍵技術

1。將 React.memo 用於功能元件

React.memo 是一個高階元件 (HOC),它透過記住結果來幫助防止功能元件中不必要的重新渲染。如果元件的 props 沒有改變,React.memo 會阻止它重新渲染。

const MyComponent = React.memo(({ data }) => {
  console.log('Component rendered');
  return <div>{data}</div>;
});
登入後複製

透過此最佳化,MyComponent 只會在其 data prop 發生變化時重新渲染,從而提高效能。

2。使用 useCallback 和 useMemo

最佳化重新渲染

?? useCallback:用於記憶函數,這樣它們就不會在每次渲染時重新建立。當將函數傳遞給依賴於特定值的子元件時,這非常有用。

const handleClick = useCallback(() => {
  // handle button click
}, []);
登入後複製

?? useMemo:用於記住昂貴的計算或派生數據,以防止在每次渲染時重新計算。

const expensiveCalculation = useMemo(() => {
  return someHeavyFunction(input);
}, [input]);
登入後複製

這些鉤子確保只有當依賴項發生變化時才會重新計算函數或值,從而減少不必要的渲染。

3。避免在 JSX 中使用內聯函數和物件建立

在 JSX 中建立的內聯函數或物件是重新渲染的常見來源。由於每次元件渲染時都會建立新的函數或物件引用,因此會在子元件中觸發不必要的重新渲染。

// Avoid this pattern
<MyChildComponent onClick={() => doSomething()} />

// Instead, define the function outside the JSX
const handleClick = () => doSomething();
<MyChildComponent onClick={handleClick} />
登入後複製

透過避免在 JSX 中建立內聯函數或對象,您可以協助防止子元件不必要地重新渲染。

4。將大組件拆分為較小的組件

避免不必要的重新渲染的另一種技術是將大型元件分解為更小、更集中的元件。這允許 React 執行更細粒度的更新,並防止在僅元件的一部分發生變更時重新渲染整個元件。

例如,如果您有一個呈現表單和清單的元件,您可以將它們拆分為兩個單獨的元件。這樣,更新表單就不會觸發清單的重新渲染,反之亦然。

function ParentComponent() {
  return (
    <>
      <FormComponent />
      <ListComponent />
    </>
  );
}
登入後複製

5。正確使用 key Prop

渲染清單時,React 使用 key 屬性來識別元素。錯誤使用 key 屬性可能會導致 React 錯誤地更新或重新渲染元件。

確保為清單中的每個元素使用唯一且穩定的鍵:

const items = ['apple', 'banana', 'orange'];
items.map((item) => <li key={item}>{item}</li>);
登入後複製

當可以重新排序或修改項目時,避免使用索引作為鍵,因為它可能會導致意外的重新渲染或不正確的渲染。

6。在類別元件中使用shouldComponentUpdate和PureComponent

對於類別元件,shouldComponentUpdate 是一種生命週期方法,可讓您控制元件是否應根據 props 或 state 的變化重新渲染。

或者,您可以使用 PureComponent,它會透過對 props 和 state 進行淺層比較來自動實作 shouldComponentUpdate。

class MyComponent extends React.PureComponent {
  render() {
    return <div>{this.props.data}</div>;
  }
}
登入後複製

PureComponent 是 shouldComponentUpdate 的更簡單替代方案,透過比較先前和目前的 props 和狀態,有助於避免不必要的重新渲染。

7。優化 Context API 使用

使用 React 的 Context API 時,請小心過度使用,因為如果每個消費者在上下文值發生變化時都重新渲染,可能會導致不必要的重新渲染。為了避免這種情況:

Break down context providers into smaller ones, so only the necessary part of the state triggers updates.
Memoize values passed to the context provider using useMemo to avoid unnecessary re-renders.

const value = useMemo(() => ({ state, updateState }), [state]);

return (
  <MyContext.Provider value={value}>
    {children}
  </MyContext.Provider>
);
登入後複製

8. Lazy Load Components

For performance improvements, especially in large applications, you can lazy load components that are not immediately needed. This can reduce the initial rendering time and the load on the main thread.

React’s React.lazy and Suspense can help in lazy-loading components:

const LazyComponent = React.lazy(() => import('./LazyComponent'));

<Suspense fallback={<div>Loading...</div>}>
  <LazyComponent />
</Suspense>
登入後複製

By lazy-loading components, you delay their rendering until they are actually needed, which reduces unnecessary renders and improves the user experience.

Conclusion

Maintaining performance in React apps requires optimizing re-rendering, especially as the application grows. Avoid needless re-renders by employing strategies like using React.memo, useCallback, useMemo, and breaking up big components into smaller ones. By putting these tactics to good use, you can make sure that your React application stays light-weight, responsive, and simple to update.

以上是優化 React 中的重新渲染:最佳實踐的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!