要最佳化 React 應用程序,您可以使用多種關鍵策略,重點關注效能、套件大小減小、高效渲染和整體用戶體驗。以下是針對 React 的最佳化技術的細分:
程式碼分割可讓您將應用程式分解為可以根據需要載入的更小的區塊,而不是一次載入整個應用程式。這縮短了初始載入時間。
const LazyComponent = React.lazy(() => import('./Component')); function App() { return ( <react.suspense fallback="{<div">Loading...}> <lazycomponent></lazycomponent> </react.suspense> ); }
避免不必要的重新渲染對於增強 React 應用程式的效能至關重要。
const MyComponent = React.memo(({ value }) => { return <div>{value}</div>; });
const computedValue = useMemo(() => expensiveComputation(value), [value]);
const handleClick = useCallback(() => { console.log('Clicked'); }, []);
以避免不必要渲染的方式處理狀態可以大大提高效能。
const [state, dispatch] = useReducer(reducer, initialState);
渲染長列表或表格會降低效能。使用清單虛擬化技術僅渲染螢幕上可見的內容。
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> );
確保您的應用程式僅匯入用於減少套件大小的庫部分。
// Instead of this: import _ from 'lodash'; // Do this: import debounce from 'lodash/debounce';
圖像通常是頁面上最大的資產。使用延遲載入來延遲載入影像,直到它們出現在視窗中。
import LazyLoad from 'react-lazyload'; const ImageComponent = () => ( <lazyload height="{200}" once> <img src="image-url.jpg" alt="優化 React 應用程式"> </lazyload> );
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}">; };
在建置過程中使用 Terser 或 Webpack 的內建縮小功能來減少 JavaScript 套件的大小。
建立 React App 自動縮小生產建置的程式碼:
npm run build
分析 JavaScript 套件的大小,以確定可以改進的領域。
npm install --save-dev webpack-bundle-analyzer
在你的 Webpack 設定中:
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer'); module.exports = { plugins: [ new BundleAnalyzerPlugin() ] };
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>
const fetchResults = debounce((query) => { // API call logic }, 300);
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>; };
Avoid adding unnecessary elements to the DOM by using React Fragments ( and >) when wrapping multiple elements.
const MyComponent = () => ( <h1>Title</h1> <p>Content</p> > );
Use the React Developer Tools profiler to identify performance bottlenecks in your app.
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中文網其他相關文章!