Skip to solution
mediumMachine Coding

Build a Lazy-loaded Image

1.1k views
01

Understand the problem

Build an image that loads only when scrolled into view.

ReactIntersectionObserverPerformance
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Solve in

Building a Lazy-loaded Image in React

Mental model: Don't set the image src until the element is about to enter the viewport. An IntersectionObserver watches a wrapper; on first intersection you assign the real src (and can stop observing). A placeholder shows until the image's onLoad fires, then you fa

Solution ready — 2 min read

Classified // press E to declassify

04

React solution

Complete solutionRun Playground
import React from 'react';
import LazyImage from './src/LazyImage';

// Tiny inline SVG data URIs so the demo needs no network.
const img = (hue) =>
  `data:image/svg+xml;utf8,` +
  encodeURIComponent(
    `<svg xmlns='http://www.w3.org/2000/svg' width='300' height='160'><rect width='100%' height='100%' fill='hsl(${hue},70%,55%)'/><text x='50%' y='50%' fill='white' font-size='20' text-anchor='middle' dominant-baseline='middle'>Image ${hue}</text></svg>`
  );

export default function App() {
  return (
    <div style={{ fontFamily: 'sans-serif', padding: 20 }}>
      <h1>Lazy Image Demo</h1>
      <p style={{ color: '#666' }}>Scroll down — each image loads as it nears the viewport.</p>
      {[10, 90, 170, 250, 330].map((h) => (
        <div key={h} style={{ marginBottom: 40 }}>
          <LazyImage src={img(h)} width={300} height={160} alt={`Image ${h}`} />
        </div>
      ))}
    </div>
  );
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 22 of 87 decoded in the Frontend Machine Coding track. One more won't hurt.

Back to track