RORK LABJP
BUILD — Rork Max runs real Macs in the cloud loaded with Xcode and the iOS SDK, writing SwiftUI, compiling, reading the errors and building again. That loop, not the code generation, is what lifts the outputNATIVE — What comes out is pure Swift and SwiftUI, not React Native. Reaching AR, Metal graphics and widgets that React Native cannot touch is the real gap between this and other buildersPLATFORMS — Coverage spans iPhone, iPad, Apple Watch, Apple TV and Vision Pro, plus iMessage. Worth a look if you want to start from a watch app or an extension rather than a phone screenCOMPANION — The Rork Companion app lets you check a generated build on a real iPhone without a paid Apple Developer account, lowering the bar for trying a first project end to endPRICING — Free to start, paid plans from $25 a month, and Rork Max on the $200 Max plan. Worth working out up front how many projects it takes to earn that backDEADLINE — From August 31, 2026, Google Play requires target API level 36 or higher for new apps and updates alike. Ten days out, and the targetSdkVersion of what you generate is yours to verifyBUILD — Rork Max runs real Macs in the cloud loaded with Xcode and the iOS SDK, writing SwiftUI, compiling, reading the errors and building again. That loop, not the code generation, is what lifts the outputNATIVE — What comes out is pure Swift and SwiftUI, not React Native. Reaching AR, Metal graphics and widgets that React Native cannot touch is the real gap between this and other buildersPLATFORMS — Coverage spans iPhone, iPad, Apple Watch, Apple TV and Vision Pro, plus iMessage. Worth a look if you want to start from a watch app or an extension rather than a phone screenCOMPANION — The Rork Companion app lets you check a generated build on a real iPhone without a paid Apple Developer account, lowering the bar for trying a first project end to endPRICING — Free to start, paid plans from $25 a month, and Rork Max on the $200 Max plan. Worth working out up front how many projects it takes to earn that backDEADLINE — From August 31, 2026, Google Play requires target API level 36 or higher for new apps and updates alike. Ten days out, and the targetSdkVersion of what you generate is yours to verify
Articles/Dev Tools
Dev Tools/2026-06-25Advanced

When an Image-Heavy Rork App Quietly Bloats Its Cache and Dies on Memory — Field Notes on Measuring and Capping

In a Rork app where images are the product, expo-image's disk cache and resident memory creep up over a session and surface as OOM crashes. Here's how I measured the bloat, where I set caps, and what I trimmed on the delivery side — with working code, in the order that actually helped.

Rork539expo-image6Memory4Caching2React Native227Performance25

Premium Article

If you run a few image-first apps as an indie developer, there comes a point where Crashlytics starts showing the same crash over and over. The repro is just "open the app, scroll the gallery for a while, zoom a few photos." The exception is always Out of memory, with no stack trace pinned to a specific screen, so the cause is hard to grab at first.

I hit this in a wallpaper app of my own. The code worked correctly, yet the longer someone used it, the more likely it was to die. The culprit was a cache that grew a little at a time. expo-image caches intelligently, but unless you design the ceiling yourself, both disk and memory keep climbing quietly. These are my notes on how I measured that growth, where I placed the caps, and what I cut on the delivery side — written in the order that paid off.

First, confirm the bloat with numbers

The worst move in a memory problem is to sprinkle clearMemoryCache() on a hunch. Clear without knowing what is consuming what, and you also tank your cache hit rate, which makes loading slow and creates a different kind of churn. Start by measuring.

expo-image does not directly report disk cache size, so I measure the cache directory with expo-file-system and turn onLoad results into metrics.

// Hook to measure load results and disk cache size
import { useCallback, useRef, useState } from 'react';
import * as FileSystem from 'expo-file-system';
 
type LoadMetrics = {
  loadCount: number;
  cacheHits: number;
  cacheHitRate: number;   // %
  avgLoadMs: number;
  diskCacheMB: number;
};
 
export const useImageMetrics = () => {
  const startTimes = useRef<Record<string, number>>({});
  const totals = useRef({ count: 0, ms: 0, hits: 0 });
  const [metrics, setMetrics] = useState<LoadMetrics>({
    loadCount: 0, cacheHits: 0, cacheHitRate: 0,
    avgLoadMs: 0, diskCacheMB: 0,
  });
 
  const markStart = useCallback((key: string) => {
    startTimes.current[key] = Date.now();
  }, []);
 
  // expo-image's onLoad returns event.cacheType ('memory' | 'disk' | 'none')
  const markLoad = useCallback((key: string, cacheType?: string) => {
    const started = startTimes.current[key] ?? Date.now();
    const ms = Date.now() - started;
    const t = totals.current;
    t.count += 1; t.ms += ms;
    if (cacheType === 'memory' || cacheType === 'disk') t.hits += 1;
    setMetrics((prev) => ({
      ...prev,
      loadCount: t.count,
      cacheHits: t.hits,
      cacheHitRate: Math.round((t.hits / t.count) * 100),
      avgLoadMs: Math.round(t.ms / t.count),
    }));
  }, []);
 
  const refreshDiskSize = useCallback(async () => {
    const dir = (FileSystem.cacheDirectory ?? '') + 'expo-image/';
    const info = await FileSystem.getInfoAsync(dir, { size: true });
    const mb = (info.exists ? (info.size ?? 0) : 0) / (1024 * 1024);
    setMetrics((prev) => ({ ...prev, diskCacheMB: Math.round(mb * 10) / 10 }));
  }, []);
 
  return { metrics, markStart, markLoad, refreshDiskSize };
};
 
// One real reading (my wallpaper app, iPhone 12, after scrolling 1,200 images):
// { loadCount: 1200, cacheHits: 1044, cacheHitRate: 87,
//   avgLoadMs: 64, diskCacheMB: 612.4 }

The first thing this revealed: cacheHitRate was a healthy 87%, yet diskCacheMB was over 600MB. The cache was working — working so well it never stopped accumulating. The problem was not the hit rate but the missing ceiling.

Cap the disk cache and delete oldest first

expo-image's clearDiskCache() wipes everything, which is too blunt for production. What you want is "delete only the overflow, oldest first." You can build that with expo-file-system by collecting each cached file's modification time and size, then deleting from the oldest once the total exceeds a threshold — an LRU-style eviction.

// Keep the disk cache under a 200MB ceiling
import * as FileSystem from 'expo-file-system';
 
const CACHE_DIR = (FileSystem.cacheDirectory ?? '') + 'images/';
const MAX_BYTES = 200 * 1024 * 1024; // 200MB
 
export const evictDiskCache = async () => {
  const dir = await FileSystem.getInfoAsync(CACHE_DIR);
  if (!dir.exists) return { freedMB: 0, keptMB: 0 };
 
  const names = await FileSystem.readDirectoryAsync(CACHE_DIR);
  const entries = await Promise.all(
    names.map(async (name) => {
      const info = await FileSystem.getInfoAsync(CACHE_DIR + name, { size: true });
      return {
        uri: CACHE_DIR + name,
        size: info.exists ? (info.size ?? 0) : 0,
        mtime: info.exists ? (info.modificationTime ?? 0) : 0, // seconds; newer = larger
      };
    })
  );
 
  const total = entries.reduce((sum, e) => sum + e.size, 0);
  if (total <= MAX_BYTES) return { freedMB: 0, keptMB: Math.round(total / 1048576) };
 
  // Oldest first (ascending mtime), drop down to 80% of the ceiling
  entries.sort((a, b) => a.mtime - b.mtime);
  let running = total;
  let freed = 0;
  const target = MAX_BYTES * 0.8;
  for (const e of entries) {
    if (running <= target) break;
    await FileSystem.deleteAsync(e.uri, { idempotent: true });
    running -= e.size; freed += e.size;
  }
  return { freedMB: Math.round(freed / 1048576), keptMB: Math.round(running / 1048576) };
};
 
// When to call: once on launch and once on returning from background.
// Example output: { freedMB: 430, keptMB: 160 }

Two details mattered here. First, drop to 80% rather than exactly the threshold. Trim to the boundary and a few more loads push you back over it, so eviction runs every time. A little headroom lowers how often you delete. Second, I limited deletion to launch and background-return. Running it mid-scroll caused the disk I/O to drop frames. Heavy cleanup belongs in the moments the user is not looking at the screen.

Thank you for reading this far.

Continue Reading

What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.

WHAT YOU'LL LEARN
An onLoad measurement hook for expo-image that surfaces cacheHitRate, average load time, and live disk cache size in MB
A manual LRU-style eviction that keeps the disk cache under a 200MB ceiling by deleting oldest files first
The recyclingKey / cachePolicy / prefetch-throttling split that cut my Crashlytics OOM rate, plus the p95 memory targets I hold the list screen to
Secure payment via Stripe · Cancel anytime

Unlock This Article

Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.

or
Unlock all articles with Membership →
Share

Thank You for Reading

Rork Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $10 for lifetime access
View Membership →

Related Articles

Dev Tools2026-06-19
When Rork-Built Lists Stutter: Designing Image Caching and Prefetch
A FlatList from Rork starts stuttering once the images pile up. Here is how I restore smoothness with expo-image caching, recyclingKey, prefetch, and a move to FlashList, with the device numbers I measured.
Dev Tools2026-08-10
Switching to Signed URLs Killed My Image Cache — Decoupling expo-image Keys from the URL
Signed URLs rewrite their query string on every expiry, so a URL-keyed cache never hits. Here is how to derive a stable key and drive expo-image's writeToCacheAsync and readFromCacheAsync yourself, with measured results.
Dev Tools2026-07-24
Collapsing Duplicate Requests Into One: A Reference-Counted Single-Flight Layer
When several components fire the same API call at launch, you get a burst of identical requests. Here is a single-flight layer that shares one in-flight promise instead: how to build the key that decides the folding, the trap of handing out a failed promise forever, the trap of one caller's abort cancelling everyone, and the test that keeps it all from regressing, with the real network numbers alongside.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →