Course contentsShow
← React Native
Lesson 212 of 1,5553. Core Primitive ComponentsFree lesson

Managing Persistent Local Storage

Learners will save UI configuration states locally between application sessions.

Managing Persistent Local Storage

In this lesson, you will learn how to keep your app’s UI settings alive even after a user closes and restarts your application.

Why Persistence Matters

By default, every time a user closes your React Native app, all the variables in your components are wiped clean. If a user sets their app to "Dark Mode" or toggles a specific view preference, that choice is lost the moment they exit. Persistent storage acts like a tiny, reliable notebook inside the user's device where your app can scribble down these configuration states to read them back later.

How to Save UI State

To save a piece of UI configuration, we typically store the data as a simple key-value pair. Think of it like a dictionary: you give a piece of data a name (the "key") and save its current value (the "value").

Whenever your component mounts, you check this storage to see if a saved value exists. If it does, you update your component’s state to match that saved setting.

Here is a simplified example of how you might toggle a saved "Dark Mode" preference:

import AsyncStorage from '@react-native-async-storage/async-storage';

// Saving a setting
const saveTheme = async (isDarkMode) => {
  try {
    await AsyncStorage.setItem('user-theme', JSON.stringify(isDarkMode));
  } catch (e) {
    // Handle saving error
  }
};

// Retrieving the setting
const getTheme = async () => {
  try {
    const value = await AsyncStorage.getItem('user-theme');
    return value ? JSON.parse(value) : false;
  } catch (e) {
    // Handle reading error
  }
};

The Workflow

  1. Initial Load: When your app starts, check the storage for a specific key (like user-theme).
  2. Sync State: If a value is found, update your local state (e.g., useState) so the UI renders correctly.
  3. Update on Change: Whenever the user toggles a UI setting, immediately save the new value to the storage so it persists for the next session.

This bridge between your app's memory and the device's disk ensures that your user's experience feels seamless and personalized every time they open your app.

Key Takeaway: Persistent storage allows your app to remember user preferences across sessions by saving UI configuration states to the device's internal memory.