React Lazy Loading は、コードをより小さなチャンクに分割し、オンデマンドでロードすることで、アプリケーションの初期バンドル サイズを削減する強力なパフォーマンス最適化手法です。このガイドでは、React アプリケーションに遅延読み込みを効果的に実装する方法を説明します。
React は、コード分割を実装するための 2 つの主要な機能を提供します。
import React, { lazy, Suspense } from 'react'; // Instead of regular import // import ExpensiveComponent from './ExpensiveComponent'; // Use lazy loading const ExpensiveComponent = lazy(() => import('./ExpensiveComponent')); function App() { return ( <Suspense fallback={<div>Loading...</div>}> <ExpensiveComponent /> </Suspense> ); }
import React, { lazy, Suspense } from 'react'; import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; // Lazy load route components const Home = lazy(() => import('./routes/Home')); const Dashboard = lazy(() => import('./routes/Dashboard')); const Profile = lazy(() => import('./routes/Profile')); function App() { return ( <Router> <Suspense fallback={<div>Loading...</div>}> <Routes> <Route path="/" element={<Home />} /> <Route path="/dashboard" element={<Dashboard />} /> <Route path="/profile" element={<Profile />} /> </Routes> </Suspense> </Router> ); }
const LoadingSpinner = () => ( <div className="loading-spinner"> <div className="spinner"></div> <p>Loading content...</p> </div> ); // Reusable lazy loading wrapper const LazyComponent = ({ component: Component, ...props }) => { return ( <Suspense fallback={<LoadingSpinner />}> <Component {...props} /> </Suspense> ); }; // Usage const MyLazyComponent = lazy(() => import('./MyComponent')); <LazyComponent component={MyLazyComponent} someProp="value" />;
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { console.error('Lazy loading error:', error, errorInfo); } render() { if (this.state.hasError) { return <div>Something went wrong. Please try again.</div>; } return this.props.children; } } // Usage with lazy loading function App() { return ( <ErrorBoundary> <Suspense fallback={<LoadingSpinner />}> <MyLazyComponent /> </Suspense> </ErrorBoundary> ); }
const MyLazyComponent = lazy(() => import('./MyComponent')); // Preload component when hovering over a button function PreloadButton() { const handleMouseEnter = () => { const componentPromise = import('./MyComponent'); // Component will start loading on hover }; return ( <button onMouseEnter={handleMouseEnter} onClick={() => setShowComponent(true)} > Show Component </button> ); }
// Too fine-grained (avoid) const Button = lazy(() => import('./Button')); // Better - lazy load feature modules const FeatureModule = lazy(() => import('./features/FeatureModule'));
// Lazy load related components together const AdminDashboard = lazy(() => import('./admin/Dashboard')); // This will load all admin components in one chunk
const LoadingFallback = () => ( <div className="loading-state"> <Skeleton /> {/* Use skeleton loading */} <ProgressBar /> {/* Show loading progress */} </div> ); function App() { return ( <Suspense fallback={<LoadingFallback />}> <MyLazyComponent /> </Suspense> ); }
const Modal = lazy(() => import('./Modal')); function App() { const [isOpen, setIsOpen] = useState(false); return ( <> <button onClick={() => setIsOpen(true)}>Open Modal</button> {isOpen && ( <Suspense fallback={<LoadingSpinner />}> <Modal onClose={() => setIsOpen(false)} /> </Suspense> )} </> ); }
function FeatureFlag({ flag, children }) { const LazyFeature = lazy(() => flag ? import('./NewFeature') : import('./OldFeature') ); return ( <Suspense fallback={<LoadingSpinner />}> <LazyFeature>{children}</LazyFeature> </Suspense> ); }
// Use webpack magic comments for better debugging const AdminPanel = lazy(() => import(/* webpackChunkName: "admin" */ './AdminPanel') );
// High-priority routes const MainContent = lazy(() => import(/* webpackPrefetch: true */ './MainContent') ); // Lower-priority features const Analytics = lazy(() => import(/* webpackPreload: true */ './Analytics') );
const trackComponentLoad = (componentName) => { // Track loading time and success performance.mark(`${componentName}-start`); return { success: () => { performance.mark(`${componentName}-end`); performance.measure( `${componentName}-load`, `${componentName}-start`, `${componentName}-end` ); }, error: (error) => { // Log error to analytics console.error(`Failed to load ${componentName}:`, error); } }; } // Usage const MyComponent = lazy(() => { const tracking = trackComponentLoad('MyComponent'); return import('./MyComponent') .then(module => { tracking.success(); return module; }) .catch(error => { tracking.error(error); throw error; }); });
React Lazy Loading は、大規模な React アプリケーションを最適化するために不可欠なツールです。これらのパターンとベスト プラクティスに従うことで、アプリケーションの初期読み込み時間と全体的なパフォーマンスを大幅に向上させることができます。
以上がReact Lazy Loading をマスターする: 完全ガイドの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。