Code splitting and lazy loading help your app load faster by only loading the code needed right now. This makes your app feel quicker and saves data.
0
0
Code splitting and lazy loading in Remix
Introduction
When your app has many pages or features that users may not visit all at once.
When you want to improve the initial load speed of your Remix app.
When you want to reduce the amount of JavaScript sent to the browser at first.
When you want to load heavy components only when the user needs them.
When you want to improve user experience on slow networks or devices.
Syntax
Remix
import { lazy, Suspense } from 'react'; const LazyComponent = lazy(() => import('./LazyComponent')); export default function MyPage() { return ( <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> ); }
Use React.lazy() to wrap the dynamic import of a component.
Wrap lazy components inside <Suspense> with a fallback UI shown while loading.
Examples
This example lazy loads a
Profile component and shows a loading message while it loads.Remix
import { lazy, Suspense } from 'react'; const Profile = lazy(() => import('./Profile')); export default function UserPage() { return ( <Suspense fallback={<div>Loading profile...</div>}> <Profile /> </Suspense> ); }
Lazy loading the
Dashboard component to speed up the home page load.Remix
import { lazy, Suspense } from 'react'; const Dashboard = lazy(() => import('./Dashboard')); export default function Home() { return ( <Suspense fallback={<div>Loading dashboard...</div>}> <Dashboard /> </Suspense> ); }
Sample Program
This Remix component lazy loads HeavyComponent. While it loads, it shows "Loading heavy content...". This keeps the app fast and responsive.
Remix
import { lazy, Suspense } from 'react'; const HeavyComponent = lazy(() => import('./HeavyComponent')); export default function App() { return ( <main> <h1>Welcome to Remix App</h1> <Suspense fallback={<p>Loading heavy content...</p>}> <HeavyComponent /> </Suspense> </main> ); }
OutputSuccess
Important Notes
Lazy loading only works for components, not for data loading in Remix loaders.
Always provide a fallback UI inside Suspense to avoid blank screens.
Code splitting helps reduce the initial JavaScript bundle size, improving performance.
Summary
Code splitting loads only the code needed right now, making apps faster.
Use React.lazy() with Suspense to lazy load components in Remix.
Always add a fallback UI to show while the lazy component loads.