0Pricing
React Native Academy · 강의

AsyncStorage로 Zustand 상태 유지하기

AsyncStorage를 기반으로 하는 persist 미들웨어로 Zustand 저장소를 감싸 앱을 다시 시작해도 상태가 유지되게 하고, 복원 시점을 처리합니다.

AsyncStorage로 Zustand 상태 유지하기은(는) CoddyKit의 무료 React Native Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 React Native Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Persist State?

By default, Zustand state lives only in memory and is lost when the app closes. Persisting state means saving it to the device's local storage so it survives app restarts. This is essential for user preferences, authentication tokens, shopping carts, or any data the user expects to still be there when they reopen the app.

Installing AsyncStorage

AsyncStorage is the standard key-value storage API for React Native. In Expo managed workflow, install the community package @react-native-async-storage/async-storage. Zustand's built-in persist middleware works with any storage adapter, and AsyncStorage is the most common choice for mobile apps.

npx expo install @react-native-async-storage/async-storage

Adding the persist Middleware

Wrap the store creator with persist imported from zustand/middleware. Pass it your store factory and a configuration object with a name key (the AsyncStorage key where state will be saved) and a storage key (pointing to your AsyncStorage adapter). Zustand handles reading and writing automatically.

import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';

export const useSettingsStore = create(
  persist<SettingsStore>(
    (set) => ({
      theme: 'light',
      notifications: true,
      setTheme: (theme) => set({ theme }),
      toggleNotifications: () =>
        set((state) => ({ notifications: !state.notifications })),
    }),
    {
      name: 'settings-store',
      storage: createJSONStorage(() => AsyncStorage),
    }
  )
);

How Persist Works Internally

When the store is first created, persist reads from AsyncStorage and rehydrates (restores) any previously saved state before rendering the first component. When state changes via set, persist automatically serializes the state to JSON and writes it to AsyncStorage asynchronously. This all happens without any extra code in your components.

Handling the Rehydration Delay

AsyncStorage reads are asynchronous, so on the first render the store may still contain the initial state before rehydration finishes. Zustand's persist middleware adds a _hasHydrated flag and an onFinishHydration callback. Use these to show a loading screen while persisted state is loading from disk.

const hasHydrated = useSettingsStore((state) => state._hasHydrated);

if (!hasHydrated) {
  return <ActivityIndicator />; // Show loading until store is ready
}

// Alternatively, listen to hydration completion:
useEffect(() => {
  const unsub = useSettingsStore.persist.onFinishHydration(() => {
    setReady(true);
  });
  return unsub;
}, []);

Persisting Only Part of the State

You often do not want to persist everything in the store — for example, transient loading states or error messages should not be saved. Use the partialize option to select which fields to persist. The returned object contains only the keys you want to write to AsyncStorage.

persist<AuthStore>(
  (set) => ({
    user: null,
    token: null,
    isLoading: false,    // transient — don't persist
    error: null,         // transient — don't persist
    login: (user, token) => set({ user, token }),
    logout: () => set({ user: null, token: null }),
  }),
  {
    name: 'auth-store',
    storage: createJSONStorage(() => AsyncStorage),
    partialize: (state) => ({ user: state.user, token: state.token }),
  }
)

Versioning and Migration

When you change the structure of your persisted state in a new app release, old data on users' devices may not match the new shape. Use the version and migrate options to upgrade stored state from one version to the next. Increment version with each structural change and handle old state in the migrate function.

persist<SettingsStore>(
  (set) => ({ /* ... */ }),
  {
    name: 'settings-store',
    storage: createJSONStorage(() => AsyncStorage),
    version: 2,
    migrate: (persistedState: any, version: number) => {
      if (version === 1) {
        // Rename darkMode to theme in version 2
        persistedState.theme = persistedState.darkMode ? 'dark' : 'light';
        delete persistedState.darkMode;
      }
      return persistedState;
    },
  }
)

Clearing Persisted State

To clear the persisted state — for example when the user logs out — call useStore.persist.clearStorage(). This removes the data from AsyncStorage. You can also call useStore.getState().reset() to clear the in-memory state at the same time. Doing both ensures the user starts fresh on the next app launch.

async function handleLogout() {
  // Clear in-memory state
  useAuthStore.getState().logout();

  // Clear persisted state from AsyncStorage
  await useAuthStore.persist.clearStorage();

  navigation.reset({ index: 0, routes: [{ name: 'Login' }] });
}

Using SecureStore for Sensitive Data

For sensitive values like auth tokens, prefer Expo SecureStore over plain AsyncStorage. SecureStore uses the device's secure enclave (iOS Keychain / Android Keystore) to encrypt data at rest. You can create a custom Zustand storage adapter using SecureStore's getItemAsync and setItemAsync methods.

import * as SecureStore from 'expo-secure-store';

const secureStorage = {
  getItem: async (name: string) => await SecureStore.getItemAsync(name),
  setItem: async (name: string, value: string) =>
    await SecureStore.setItemAsync(name, value),
  removeItem: async (name: string) =>
    await SecureStore.deleteItemAsync(name),
};

// Use secureStorage instead of AsyncStorage:
storage: createJSONStorage(() => secureStorage),

Debugging Persisted State

To inspect what is stored in AsyncStorage during development, call AsyncStorage.getAllKeys() and AsyncStorage.multiGet(keys) in the dev console or a debug screen. You can also manually clear stale persisted state with AsyncStorage.clear() when testing migration logic. Always test with a fresh install to simulate real user upgrade scenarios.

// Debug helper — call from a dev-only screen
async function printStorage() {
  const keys = await AsyncStorage.getAllKeys();
  const pairs = await AsyncStorage.multiGet(keys);
  pairs.forEach(([key, value]) => {
    console.log(key, ':', JSON.parse(value ?? 'null'));
  });
}

Persisting a Cart Store Example

Here is a realistic cart store that persists its items list across app restarts. Loading and error state are excluded from persistence using partialize. The total is derived on the fly in the component rather than stored, so it is always consistent with the items array after rehydration.

export const useCartStore = create(
  persist<CartStore>(
    (set, get) => ({
      items: [],
      addItem: (item) => set((state) => ({ items: [...state.items, item] })),
      removeItem: (id) =>
        set((state) => ({ items: state.items.filter((i) => i.id !== id) })),
      clearCart: () => set({ items: [] }),
    }),
    {
      name: 'cart-store',
      storage: createJSONStorage(() => AsyncStorage),
      partialize: (state) => ({ items: state.items }),
    }
  )
);

Quick Check

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

Lesson Recap

In this lesson you learned: the persist middleware wraps a Zustand store to save and restore state from AsyncStorage automatically, partialize controls which fields are persisted to avoid saving transient loading or error state, and version with migrate handles breaking state shape changes across app updates. Next up we explore the slices pattern and Devtools integration in Zustand.

자주 묻는 질문

“AsyncStorage로 Zustand 상태 유지하기” 강의는 무료인가요?

네 — “AsyncStorage로 Zustand 상태 유지하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 React Native Academy 강의 전체를 잠금 해제할 수 있습니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“AsyncStorage로 Zustand 상태 유지하기”에서 뭘 배우나요?

AsyncStorage를 기반으로 하는 persist 미들웨어로 Zustand 저장소를 감싸 앱을 다시 시작해도 상태가 유지되게 하고, 복원 시점을 처리합니다. 브라우저에서 직접 실행하는 실습 코드로 React Native Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

React Native Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 React Native Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“AsyncStorage로 Zustand 상태 유지하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 React Native Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 React Native Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Zustand 저장소 만들기
  2. 컴포넌트에서 저장소 상태 읽고 업데이트하기
  3. AsyncStorage로 Zustand 상태 유지하기
  4. 슬라이스 패턴과 Devtools 통합
← React Native Academy(으)로 돌아가기