Coding exercise: implement lazy loading in React.

React practical coding · Freshers and experienced

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

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