0Pricing
React Native Academy · บทเรียน

การคงแคชคำค้นด้วย AsyncStorage

ติดตั้งปลั๊กอินการคงข้อมูลของ React Query จัดเก็บแคชคำค้นทั้งหมดใน AsyncStorage และกู้คืนเมื่อเริ่มแอป เพื่อให้ข้อมูลพร้อมใช้งานทันทีแม้ออฟไลน์

การคงแคชคำค้นด้วย AsyncStorage เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน React Native Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Persist the Query Cache?

By default the React Query cache exists only in memory. When the app is closed and reopened, all cached data is gone — the user sees loading spinners while data refetches from the network. On slow or absent connections, this means a blank screen.

Cache persistence saves the React Query cache to disk (AsyncStorage on React Native) so data is available immediately on the next app launch, before any network requests complete. This is the foundation of offline-first mobile applications.

Required Packages

Cache persistence requires three packages: @tanstack/react-query (core), @tanstack/react-query-persist-client (the persistence adapter), and a persister implementation. For React Native we use @tanstack/async-storage-persister which wraps AsyncStorage as the persistence backend.

AsyncStorage is the standard key-value store for React Native, provided by @react-native-async-storage/async-storage. The persister serializes the entire query cache to JSON and writes it to a single AsyncStorage key.

// Install all required packages:
// npx expo install @tanstack/react-query
// npx expo install @tanstack/react-query-persist-client
// npx expo install @tanstack/async-storage-persister
// npx expo install @react-native-async-storage/async-storage

import { createAsyncStoragePersister } from '@tanstack/async-storage-persister';
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client';
import AsyncStorage from '@react-native-async-storage/async-storage';

Creating the Persister

Create a persister instance with createAsyncStoragePersister, passing the AsyncStorage instance and a storage key name. The persister serializes the React Query cache to JSON and writes it to that key whenever the cache changes.

The persister also has a throttleTime option (default 1000ms) that prevents writing to AsyncStorage too frequently during rapid state changes. Increase it if you notice excessive I/O or battery drain.

import { createAsyncStoragePersister } from '@tanstack/async-storage-persister';
import AsyncStorage from '@react-native-async-storage/async-storage';

const asyncStoragePersister = createAsyncStoragePersister({
  storage: AsyncStorage,
  key: 'react-query-cache', // AsyncStorage key to use
  throttleTime: 1000,        // ms between writes (default)
  serialize: JSON.stringify, // custom serializer (optional)
  deserialize: JSON.parse,   // custom deserializer (optional)
});

PersistQueryClientProvider

Replace the standard QueryClientProvider with PersistQueryClientProvider. Pass both the client (your QueryClient) and persistOptions (containing the persister). The provider handles restoring the cache on startup and saving it on changes automatically.

During restoration, the component tree is rendered with the cached data immediately — no loading state on first paint. React Query also schedules a background refetch to get fresh data from the server.

import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client';

export default function App() {
  return (
    <PersistQueryClientProvider
      client={queryClient}
      persistOptions={{ persister: asyncStoragePersister }}
    >
      <NavigationContainer>
        <RootNavigator />
      </NavigationContainer>
    </PersistQueryClientProvider>
  );
}

maxAge: Cache Expiry

The persisted cache can become outdated over time. Configure maxAge in persistOptions to set how long persisted data is considered valid. Older data is discarded and fresh data is fetched from the network on next launch. The default maxAge is 24 hours.

Choose maxAge based on how quickly your data changes. For user profile data that rarely changes, 7 days might be appropriate. For news feeds that change constantly, 30 minutes keeps the cache useful without serving very stale content.

<PersistQueryClientProvider
  client={queryClient}
  persistOptions={{
    persister: asyncStoragePersister,
    maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days in ms
    // Cache older than 7 days is discarded on launch
  }}
>

buster: Invalidating Old Cache Versions

When you release a new app version with changed data structures, the old cached format may be incompatible. The buster option in persistOptions is a version string — when it changes, the old persisted cache is discarded and a fresh fetch begins.

Update the buster string whenever you make breaking changes to your API responses or query key structure. A common pattern is to use the app version number from expo-constants or a manually managed version string.

import Constants from 'expo-constants';

<PersistQueryClientProvider
  client={queryClient}
  persistOptions={{
    persister: asyncStoragePersister,
    maxAge: 24 * 60 * 60 * 1000,
    buster: Constants.expoConfig.version, // bust cache on app update
  }}
>

// Or use a manual API version:
// buster: 'api-v3', // update when API structure changes

Handling Rehydration Loading State

Cache restoration from AsyncStorage is asynchronous. During this brief period (usually milliseconds) the app might flash with empty data before the cache is restored. PersistQueryClientProvider provides an onSuccess callback that fires when rehydration completes.

Show a splash screen or skeleton UI until rehydration is done, then reveal the app. This prevents the jarring empty-to-full transition that happens if you render before the cache is ready.

const [isRestored, setIsRestored] = React.useState(false);

<PersistQueryClientProvider
  client={queryClient}
  persistOptions={{ persister: asyncStoragePersister }}
  onSuccess={() => setIsRestored(true)}
>
  {isRestored ? (
    <NavigationContainer>
      <RootNavigator />
    </NavigationContainer>
  ) : (
    <SplashScreen />
  )}
</PersistQueryClientProvider>

Selective Persistence with Meta

Not all queries should be persisted. Sensitive data (user payment info), session-specific data, or very large datasets may not be appropriate to save to local storage. Use the gcTime: 0 option to exclude specific queries from persistence — they are garbage collected immediately when unmounted and never written to disk.

Alternatively, configure a custom dehydrateState function in persistOptions to filter which queries are included in the persisted snapshot.

// This query is excluded from persistence (never cached to disk):
const { data: paymentInfo } = useQuery({
  queryKey: ['payment-info'],
  queryFn: fetchPaymentInfo,
  gcTime: 0,        // no memory cache either
  staleTime: 0,     // always refetch
});

// This query is persisted normally:
const { data: userProfile } = useQuery({
  queryKey: ['profile'],
  queryFn: fetchProfile,
  staleTime: 5 * 60 * 1000,
});

Offline Behavior with Persisted Cache

With cache persistence enabled, users who open the app offline see cached data immediately — no loading state, no empty lists. React Query knows the data might be stale and schedules a network refetch, but it displays the cache while waiting for the connection.

Configure networkMode: 'offlineFirst' on queries that should work offline. The default mode pauses queries when offline; offlineFirst returns cached data even when offline without throwing an error.

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      networkMode: 'offlineFirst', // serve cache even when offline
      staleTime: 5 * 60 * 1000,
      retry: false, // don't retry when offline
    },
  },
});

// Individual query override:
const { data } = useQuery({
  queryKey: ['articles'],
  queryFn: fetchArticles,
  networkMode: 'always', // always try network
});

Cache Size and Storage Limits

AsyncStorage has size limits (typically 6MB per key on iOS, varies by device on Android). Persisting a large React Query cache with many queries can approach these limits. Monitor cache size using serialized length: JSON.stringify(dehydratedState).length.

Strategies to manage cache size: reduce gcTime so unused queries are garbage collected quickly before serialization, limit the number of cached items per list (use pages in infinite queries), and exclude large binary or image data from cache.

// Check cache size in development:
AsyncStorage.getItem('react-query-cache').then((data) => {
  if (data) {
    const sizeKB = data.length / 1024;
    console.log('Cache size:', sizeKB.toFixed(1), 'KB');
    if (sizeKB > 4000) {
      console.warn('Cache approaching AsyncStorage limit!');
    }
  }
});

// Manually clear the cache if needed:
queryClient.clear();
await AsyncStorage.removeItem('react-query-cache');

Combining Persistence with Network Status

A complete offline-first setup combines cache persistence with network status detection. Use a network status hook to detect connectivity changes, and use React Query's onlineManager to notify the library when the device goes online/offline. This prevents background refetches while offline and triggers them when connectivity returns.

This combination gives users a seamless experience: app opens with cached data, shows a subtle offline indicator when disconnected, and silently refreshes when connectivity returns.

import NetInfo from '@react-native-community/netinfo';
import { onlineManager } from '@tanstack/react-query';

// At app startup:
NetInfo.addEventListener((state) => {
  onlineManager.setOnline(state.isConnected);
});

// Queries will automatically:
// - Pause when offline
// - Resume and refetch when online
// - Serve cache while waiting

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: PersistQueryClientProvider with createAsyncStoragePersister saves the entire React Query cache to AsyncStorage for offline-first behavior, buster invalidates stale cache formats when you ship API changes, and gcTime: 0 on individual queries excludes sensitive data from being persisted to local storage. Next up we configure staleTime, background refetch, and network reconnect behavior for a polished offline experience.

คำถามที่พบบ่อย

บทเรียน “การคงแคชคำค้นด้วย AsyncStorage” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การคงแคชคำค้นด้วย AsyncStorage” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การคงแคชคำค้นด้วย AsyncStorage”

ติดตั้งปลั๊กอินการคงข้อมูลของ React Query จัดเก็บแคชคำค้นทั้งหมดใน AsyncStorage และกู้คืนเมื่อเริ่มแอป เพื่อให้ข้อมูลพร้อมใช้งานทันทีแม้ออฟไลน์ คุณปฏิบัติ React Native Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน React Native Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน React Native Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การคงแคชคำค้นด้วย AsyncStorage” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน React Native Academy นี้ได้ไหม

ได้ บทเรียน React Native Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. QueryClient, QueryClientProvider และ useQuery
  2. การเปลี่ยนแปลงด้วย useMutation และการทำให้แคชไม่ถูกต้อง
  3. การคงแคชคำค้นด้วย AsyncStorage
  4. การดึงข้อมูลเบื้องหลังและการกำหนดเวลาข้อมูลเก่า
← กลับไปที่ React Native Academy