Coding exercise: implement lazy loading in React.
Model answer
Lazy loading means downloading code or images only when needed. For components use React.lazy with Suspense, usually per route. For images use the native loading attribute.
const Settings = lazy(() => import('./pages/Settings'));
function App() {
return (
<Suspense fallback={<p>Loading…</p>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</Suspense>
);
}
// Images below the fold
<img src={url} alt="Team photo" loading="lazy" width="400" height="300" />The Settings code is only downloaded when someone opens that route. Width and height stop the page jumping as images load. Do not lazy-load things visible at first paint, because that makes the page slower.
Tips
- The lazy component must be a default export.
Practise it yourself in the React and Angular code playground.
Learn this topic
React.js Full Course: Beginner to Advanced .
Sign in to add your own answer.
More questions
- Coding exercise: build a Todo application in React.
- Coding exercise: create a search box with debounce in React.
- Coding exercise: fetch API data and display it in a table in React.
- Coding exercise: implement pagination in React.
- Coding exercise: create a login form with validation in React.
- Coding exercise: build a parent-child communication example in React.