React
Lazy Loading
Code splitting and lazy loading.
By EZ4Code Team
reactlazy
Code
import { lazy, Suspense, useState } from 'react';
// Lazy load component
const Dashboard = lazy(() => import('./Dashboard'));
const Settings = lazy(() => import('./Settings'));
const Profile = lazy(() => import('./Profile'));
function App() {
const [page, setPage] = useState('dashboard');
return (
<div>
<nav>
<button onClick={() => setPage('dashboard')}>Dashboard</button>
<button onClick={() => setPage('settings')}>Settings</button>
<button onClick={() => setPage('profile')}>Profile</button>
</nav>
<Suspense fallback={<div>Loading...</div>}>
{page === 'dashboard' && <Dashboard />}
{page === 'settings' && <Settings />}
{page === 'profile' && <Profile />}
</Suspense>
</div>
);
}
// Multiple components sharing Suspense
function App2() {
return (
<Suspense fallback={<Spinner />}>
<Header />
<Suspense fallback={<ContentLoader />}>
<MainContent />
</Suspense>
<Footer />
</Suspense>
);
}
// Preload
const lazyWithPreload = (factory) => {
const Component = lazy(factory);
Component.preload = factory;
return Component;
};
const HeavyChart = lazyWithPreload(() => import('./HeavyChart'));
// Preload on hover
<button onMouseEnter={() => HeavyChart.preload()}>
Show Chart
</button>Explanation
React.lazy with Suspense implements component lazy loading, reducing initial bundle size; fallback shows loading state.
More React Snippets
Controlled Form with Validation
Build a controlled React form with inline validation and error messages.
Event Handling and List Rendering
Handle events and render dynamic lists with keys in React.
useState
State management Hook.
useEffect
Side-effect Hook.
useContext
Shared state via context.
useReducer
Complex state management.