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

優化 React 應用程式

PHPz
發布: 2024-09-08 20:30:31
原創
439 人瀏覽過

Optimize React Application

要最佳化 React 應用程序,您可以使用多種關鍵策略,重點關注效能、套件大小減小、高效渲染和整體用戶體驗。以下是針對 React 的最佳化技術的細分:

1. 程式碼分割

程式碼分割可讓您將應用程式分解為可以根據需要載入的更小的區塊,而不是一次載入整個應用程式。這縮短了初始載入時間。

  • React.lazy:使用React內建的延遲載入功能動態匯入元件。
  const LazyComponent = React.lazy(() => import('./Component'));

  function App() {
    return (
      <react.suspense fallback="{<div">Loading...}>
        <lazycomponent></lazycomponent>
      </react.suspense>
    );
  }
登入後複製
  • React Loadable:或者,您可以使用像 react-loadable 這樣的函式庫來獲得更進階的程式碼分割選項。

2. 記憶並防止不必要的重新渲染

避免不必要的重新渲染對於增強 React 應用程式的效能至關重要。

  • React.memo:用 React.memo 包裹功能元件,以防止它們在 props 沒有改變的情況下重新渲染。
  const MyComponent = React.memo(({ value }) => {
    return <div>{value}</div>;
  });
登入後複製
  • useMemo:記住昂貴的計算,以便除非必要,否則不會在每次渲染時重新計算它們。
  const computedValue = useMemo(() => expensiveComputation(value), [value]);
登入後複製
  • useCallback:記憶函數以避免每次都傳遞新引用,特別是在子組件或效果中用作依賴項時。
  const handleClick = useCallback(() => {
    console.log('Clicked');
  }, []);
登入後複製

3. 使用高效率的狀態管理

以避免不必要渲染的方式處理狀態可以大大提高效能。

  • useReducer:對於複雜的狀態邏輯,請考慮使用 useReducer 而不是 useState 來更好地控制狀態變更。
  const [state, dispatch] = useReducer(reducer, initialState);
登入後複製
  • 元件分割:分割元件,以便在狀態變更時僅重新渲染必要的部分。

4. 虛擬化長列表

渲染長列表或表格會降低效能。使用清單虛擬化技術僅渲染螢幕上可見的內容。

  • react-windowreact-virtualized:這些函式庫可讓您透過虛擬化清單來有效渲染大型資料集。
  import { FixedSizeList as List } from 'react-window';

  const MyList = ({ items }) => (
    <list height="{500}" itemcount="{items.length}" itemsize="{35}" width="{300}">
      {({ index, style }) => <div style="{style}">{items[index]}</div>}
    </list>
  );
登入後複製

5. 搖樹

確保您的應用程式僅匯入用於減少套件大小的庫部分。

  • ES6 導入:僅從函式庫(如 lodash、moment.js 等)匯入您需要的模組,而不是整個函式庫。
  // Instead of this:
  import _ from 'lodash';

  // Do this:
  import debounce from 'lodash/debounce';
登入後複製

6. 延遲載入圖片

圖像通常是頁面上最大的資產。使用延遲載入來延遲載入影像,直到它們出現在視窗中。

  • react-lazyload:使用 react-lazyload 函式庫進行簡單的圖片延遲載入。
  import LazyLoad from 'react-lazyload';

  const ImageComponent = () => (
    <lazyload height="{200}" once>
      <img src="image-url.jpg" alt="優化 React 應用程式">
    </lazyload>
  );
登入後複製
  • Intersection Observer:您也可以使用 Intersection Observer API 在圖片進入視圖時延遲載入圖片。
  const LazyImage = ({ src, alt }) => {
    const [inView, setInView] = useState(false);
    const imgRef = useRef(null);

    useEffect(() => {
      const observer = new IntersectionObserver(([entry]) => {
        if (entry.isIntersecting) {
          setInView(true);
          observer.disconnect();
        }
      });
      observer.observe(imgRef.current);
    }, []);

    return <img ref="{imgRef}" src="%7BinView" : alt="{alt}">;
  };
登入後複製

7. 縮小 JavaScript

  • 在建置過程中使用 Terser 或 Webpack 的內建縮小功能來減少 JavaScript 套件的大小。

  • 建立 React App 自動縮小生產建置的程式碼:

  npm run build
登入後複製

8. 捆綁分析

分析 JavaScript 套件的大小,以確定可以改進的領域。

  • 使用 webpack-bundle-analyzer 視覺化您的套件並查看哪些程式庫佔用了最多的空間。
  npm install --save-dev webpack-bundle-analyzer
登入後複製

在你的 Webpack 設定中:

  const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
  module.exports = {
    plugins: [
      new BundleAnalyzerPlugin()
    ]
  };
登入後複製

9. 減少未使用的CSS

  • 使用 PurgeCSS 等工具從套件中移除未使用的 CSS。您可以將其與 Webpack 或 PostCSS 設定整合。
  npm install @fullhuman/postcss-purgecss
登入後複製

PostCSS 設定範例:

  const purgecss = require('@fullhuman/postcss-purgecss')({
    content: ['./src/**/*.js', './public/index.html'],
    defaultExtractor: content => content.match(/[\w-/:]+(?



<h3>
  
  
  10. <strong>最佳化網路請求</strong>
</h3>

<p>減少網路請求數量和最佳化 API 呼叫可以帶來顯著的效能提升。 </p>

登入後複製
  • Debouncing API Calls: Use debouncing to limit how often API requests are sent during user input.
  const fetchResults = debounce((query) => {
    // API call logic
  }, 300);
登入後複製
  • Caching API Data: Use libraries like SWR or React Query to cache API requests and avoid refetching data unnecessarily.
  import useSWR from 'swr';

  const fetcher = url => fetch(url).then(res => res.json());

  const MyComponent = () => {
    const { data, error } = useSWR('/api/data', fetcher);

    if (error) return <div>Error loading data</div>;
    if (!data) return <div>Loading...</div>;
    return <div>{data.message}</div>;
  };
登入後複製

11. Use React Fragments

Avoid adding unnecessary elements to the DOM by using React Fragments ( and >) when wrapping multiple elements.

const MyComponent = () => (
  
    <h1>Title</h1>
    <p>Content</p>
  >
);
登入後複製

12. Profiling and Performance Testing

Use the React Developer Tools profiler to identify performance bottlenecks in your app.

  • React Profiler: In Chrome or Firefox, open the React DevTools and switch to the "Profiler" tab. Record a session and analyze where components are re-rendering and consuming more time.

Conclusion

Optimizing a React application requires careful attention to performance, bundle size, and rendering efficiency. By employing techniques like code splitting, memoization, lazy loading, tree shaking, and minimizing network requests, you can significantly improve the performance of your app. Make sure to regularly analyze and test your app’s performance to catch any potential inefficiencies.

以上是優化 React 應用程式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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