Loading a component on demand
Not every part of a screen is needed on the first paint. A comments panel, a
settings tab, a modal — someone may never open them. lazy lets you split a
component's code into a separate chunk and load it only when it is rendered. It
takes a factory that returns a promise resolving to a module with a default
export — normally a dynamic import():
import { lazy, Suspense } from 'react';
const Comments = lazy(() => import('./Comments'));
The first time <Comments /> renders, React sees that the code has not loaded
and suspends. Wrap it in a <Suspense> boundary to show a fallback while
the chunk is in flight:
<Suspense fallback={<p>Loading…</p>}>
<Comments />
</Suspense>
When the promise resolves, React swaps the fallback for the real component and
never suspends on it again. lazy is a dynamic import plus the Suspense
machinery you already know. Because the template for this Lesson is a single
file, the factory resolves a component directly instead of importing a real
chunk, but the mechanics are identical.
Keep lazy components at the edges of your tree — a route, a tab, a modal — so the first paint is not blocked by code someone may never need.
Your job is to lazy-load a component behind a fallback.
Challenge
Part of a screen is not needed until it is shown, and it should not weigh down the
first paint. Export an App component from App.jsx that creates a lazy
component with lazy, whose factory resolves to a component rendering
<p>Hello</p>. Render it inside a <Suspense> boundary with the fallback
<p>Loading…</p>.
The Test expects Loading… first, then Hello once the lazy component loads.
The starter renders Loading… and never loads anything, so the Test fails.