mediumReact Native#18

Image caching and preloading

Prompt

Implement an image gallery that preloads the next image while displaying the current one. Use Image.prefetch for preloading. Show a loading placeholder while an image loads.

Solution

const [index, setIndex] = useState(0)
useEffect(() => {
  if (index < IMAGES.length - 1) Image.prefetch(IMAGES[index + 1])
}, [index])
return (
  <View>
    <Image source={{ uri: IMAGES[index] }} style={{ width: 400, height: 300 }}
      defaultSource={require('./placeholder.png')} />
    <Button title="Next" onPress={() => setIndex(i => Math.min(i + 1, IMAGES.length - 1))} />
  </View>
)
Mentor's take

Prefetching converts wait time the user will experience into background work they never see: while they look at image N, Image.prefetch(IMAGES[index + 1]) pulls N+1 into the native image cache (keyed by URL), so tapping Next resolves from disk instead of the network. Keying the effect on index makes the strategy incremental — always one step ahead, never downloading the whole gallery speculatively, which respects mobile bandwidth and memory.

The details that separate shipping code from demo code: the boundary check stops prefetching past the last image; Math.min clamps navigation the same way; defaultSource shows a bundled placeholder synchronously — it's a local require, available at first paint, no network involved. Note prefetch returns a promise you can ignore for warming but await when you must guarantee readiness (e.g. before a transition).

The honest scope statement: core Image caching is coarse — you don't control cache size or eviction, and Android's behavior has historically been weaker. Production galleries reach for expo-image (or FastImage historically) for explicit cachePolicy, priorities, and recycling — same prefetch-next architecture, better cache control.

Red flag: prefetching the entire list on mount. On a metered connection that's user-hostile, and the memory/disk cost buys nothing the incremental strategy doesn't.

Say it: "I prefetch exactly one step ahead of the user into the native cache and show a bundled placeholder meanwhile — incremental warming, not speculative bulk download."