React · Lesson 72 of 120
Suspense and lazy
Load parts later.
Big apps ship a lot of code. Not all of it is needed straight away. Lazy loading downloads a component only when it's first shown, and suspense shows something while it loads.
- Lots of code
- Not needed yet
- Load it later
Lazy reviews
Lazy loads a component's code only when it's first needed. Suspense shows a fallback while that code is loading. The reviews aren't downloaded until the button is clicked. That keeps the first page load small. We show the reviews. Run it.
App.jsxjsx
import { lazy, Suspense, useState } from "react";
const Reviews = lazy(() => import("./Reviews"));
export default function App() {
const [show, setShow] = useState(false);
return (
<div className="box">
<h2>Trail 500</h2>
<button id="r" onClick={() => setShow(true)}>Show reviews</button>
{show && (
<Suspense fallback={<p>Loading reviews...</p>}>
<Reviews />
</Suspense>
)}
</div>
);
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses Reviews.jsx
export default function Reviews() {
return <ul><li>★★★★★ Great on muddy trails — Sam</li><li>★★★★ Light and quick — Jo</li></ul>;
}Also uses actions.json
[{"click": "#r"}, {"wait": 300}]Suspense boundaries
A suspense boundary catches anything below it that's still loading. Lazy components, and data read with the use hook. Put boundaries where a loading message makes sense, not around every component.
| key | value |
|---|---|
| lazy() | code on demand |
| <Suspense> | fallback while loading |
| Catches | anything below |
| Place | where it makes sense |
Summary
Lazy loads code on demand, and suspense shows a fallback meanwhile. Next, a new section starting with error boundaries.
Key takeaways- lazy(() => import())
- <Suspense fallback>
- Smaller start
Next up: Error Boundaries — catch crashes