1---
2title: Conditional Module Loading
3impact: HIGH
4impactDescription: loads large data only when needed
5tags: bundle, conditional-loading, lazy-loading
6---
7
8## Conditional Module Loading
9
10Load large data or modules only when a feature is activated.
11
12**Example (lazy-load animation frames):**
13
14```tsx
15function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
16 const [frames, setFrames] = useState<Frame[] | null>(null)
17
18 useEffect(() => {
19 if (enabled && !frames && typeof window !== 'undefined') {
20 import('./animation-frames.js')
21 .then(mod => setFrames(mod.frames))
22 .catch(() => setEnabled(false))
23 }
24 }, [enabled, frames, setEnabled])
25
26 if (!frames) return <Skeleton />
27 return <Canvas frames={frames} />
28}
29```
30
31The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.