A unified caching layer for React Native with a simple API, TTL support, and multiple storage backends.
Cache JSON/data with hooks (useCached, useCachedFetchJSON) Cache images to file system transparently (useCachedImage) Plug-and-play storages: Memory, AsyncStorage, optional File System (via react-native-fs) Install npm i react-native-smart-cache @react-native-async-storage/async-storage
npm i -S react-native-fs Quick Start Wrap your app:
import React from 'react'; import { CacheProvider } from 'react-native-smart-cache'; import { AsyncStorageAdapter } from 'react-native-smart-cache';
export default function App() { return ( <CacheProvider storage={new AsyncStorageAdapter()} namespace="appcache"> {/* ... your app ... */} ); } Cache JSON via HTTP:
import { useCachedFetchJSON } from 'react-native-smart-cache';
function Todos() { const { data, loading, error, refetch } = useCachedFetchJSON('https://jsonplaceholder.typicode.com/todos');
if (loading && !data) return Loading...; if (error) return Failed; return ( <> {data?.slice(0,5).map((t:any) => {t.title})} </> ); } Cache remote images to disk:
import { Image } from 'react-native'; import { useCachedImage } from 'react-native-smart-cache';
function Avatar({ url }: { url: string }) { const { uri, loading } = useCachedImage(url); if (!uri) return null; return <Image source={{ uri }} style={{ width: 64, height: 64, borderRadius: 32 }} />; } API <CacheProvider storage?: IStorage; namespace?: string /> useSmartCache() → access low-level SmartCache instance useCached(key, fetcher, ttlMs?) → cache any async result useCachedFetchJSON(url, ttlMs?, init?) useCachedImage(url, ttlMs?) SmartCache class SmartCache { constructor(storage: IStorage, namespace?: string); get(key: string): Promise<T | null>; getEntry(key: string): Promise<CacheEntry | null>; set(key: string, value: T, ttlMs?: number | null): Promise; remove(key: string): Promise; clearAll(): Promise; } Storages MemoryStorage(capacity?: number) – in-memory LRU (count-based) AsyncStorageAdapter – persistent key-value storage FSStorage(baseDir?: string) – file-based storage (requires react-native-fs) Notes TTL: pass null to persist indefinitely. useCached returns cached data immediately (if any), then refreshes in background. useCachedImage stores the file in caches directory; if react-native-fs is not installed, it falls back to the original URL. Roadmap Cache size policies (bytes-based LRU) Batch prefetching & warmers Devtools overlay (view cache, purge by key/prefix) Query invalidation by tags Offline mutation queue