Open In App

React Native AsyncStorage Component

Last Updated : 10 May, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Here is a guide on how to use AsyncStorage in React Native. We will use the AsyncStorage component. AsyncStorage is an unencrypted, asynchronous, persistent key-value storage system that is accessible globally throughout the app.

Syntax

AsyncStorage.method();

Methods in AsyncStorage

Method

Description

getItem()

It fetches an item for a key.

setItem()

It sets an item for a particular key.

removeItem()

It removes an item for a key.

mergeItem()

It merges an existing key-value with an input value.

clear()

It erases all AsyncStorage for all clients, libraries, etc.

getAllKeys()

It will get all keys known to your app.

flushGetRequests()

It flushes any pending requests using a single batch call to get the data.

multiGet()

This allows you to batch the fetching of items given an array of key inputs.

multiSet()

It uses this as a batch operation for storing multiple key-value pairs.

multiRemove()

It removes all keys from the keys array.

multiMerge()

It is a batch operation to merge existing and new values for a given set of keys.

Now let’s start with the implementation.


Step-by-Step Implementation

Step 1: Create a React Native Project

Now, create a project with the following command.

npx create-expo-app app-name --template

Note: Replace the app-name with your app name for example : react-native-demo-app

Next, you might be asked to choose a template. Select one based on your preference as shown in the image below. I am selecting the blank template because it will generate a minimal app, as clean as an empty canvas in JavaScript.

It completes the project creation and displays a message: "Your Project is ready!" as shown in the image below.

Now go into your project folder, i.e., react-native-demo

cd app-name

Project Structure

Step 2: Run  Application

Start the server by using the following command.

npx expo start

Then, the application will display a QR code.

  • For the Android users,
    • For the Android Emulator, press "a" as mentioned in the image below.
    • For Physical Device, Download the "Expo Go" app from the Play Store. Open the app, and you will see a button labeled "Scan QR Code." Click that button and scan the QR code; it will automatically build the Android app on your device.
  • For iOS users, simply scan the QR code using the Camera app.
  • If you're using a web browser, it will provide a local host link that you can use as mentioned in the image below.

Step 3: Start Coding

- Import libraries: Import required libraries at the top of the file.

Here, we are going to use "@react-native-async-storage/async-storage" library for AsyncStorage, But before Using it install it with command below.

npm install @react-native-async-storage/async-storage

Now, Import!

JavaScript
// Import necessary libraries
import React, { useState } from "react";
// Import components from React Native
import { StyleSheet, Text, View, Button } from "react-native";
// Import AsyncStorage for local storage
import AsyncStorage from "@react-native-async-storage/async-storage";


- StyleSheet: Create a StyleSheet to style the components like container, text, and button.

JavaScript
// Styles for the components
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  text: {
    fontSize: 40,
    marginBottom: 30,
  },
  button: {
    margin: 20,
    width: 250,
  },
});


- Buttons: Create a couple of buttons inside the App Component named as "add" and "get".

  • add: Used to call a function that adds the data to AsyncStorage.
  • get: Used to call a function that retrieves data from AsyncStorage.
JavaScript
// Main App component
export default function App() {

  return (
    <View style={styles.container}>
      {/* Display retrieved data */}
      <Text style={styles.text}>{data}</Text>
      {/* Button to add data */}
      <View style={styles.button}>
        <Button title={"add"} onPress={add} />
      </View>
      {/* Button to get data */}
      <View style={styles.button}>
        <Button title={"get"} onPress={get} />
      </View>
    </View>
  );
}


- add function: Used to add data to AsyncStorage.

JavaScript
// Function to add data to AsyncStorage
const add = async () => {
    try {
        // Store key-value pair in AsyncStorage
        await AsyncStorage.setItem("gfg", "GeeksforGeeks"); 
    } catch (e) {
        // Log any errors
        console.error(e); 
    }
};


- get function: Used to retrieve data from AsyncStorage and update the state.

JavaScript
// Function to retrieve data from AsyncStorage
const get = async () => {
    try {
        // Retrieve value by key
        const value = await AsyncStorage.getItem("gfg"); 
        if (value !== null) {
            // Update state with retrieved value
            setdata(value); 
        }
    } 
    catch (e) {
        // Log any errors
        console.error(e); 
    }
};


- useState: Update the state using the code below and add the updated state value in the components.

JavaScript
// State to store retrieved data
const [data, setdata] = useState(""); 


{/* Display retrieved data */}
<Text style={styles.text}>{data}</Text>


To know more about useState in React Native refer this article: React useState Hook.

Here we created two buttons, the first button Set the value and the second button Fetch the value.

Complete Source Code:

App.js

App.js
// Import necessary libraries
import React, { useState } from "react";
// Import components from React Native
import { StyleSheet, Text, View, Button } from "react-native";
// Import AsyncStorage for local storage
import AsyncStorage from "@react-native-async-storage/async-storage";

// Main App component
export default function App() {
  
  // State to store retrieved data
  const [data, setdata] = useState(""); 

  // Function to add data to AsyncStorage
  const add = async () => {
    try {
      // Store key-value pair in AsyncStorage
      await AsyncStorage.setItem("gfg", "GeeksforGeeks"); 
    } catch (e) {
      // Log any errors
      console.error(e); 
    }
  };

  // Function to retrieve data from AsyncStorage
  const get = async () => {
    try {
      // Retrieve value by key
      const value = await AsyncStorage.getItem("gfg"); 
      if (value !== null) {
        // Update state with retrieved value
        setdata(value); 
      }
    } catch (e) {
      // Log any errors
      console.error(e); 
    }
  };

  return (
    <View style={styles.container}>
      {/* Display retrieved data */}
      <Text style={styles.text}>{data}</Text>
      {/* Button to add data */}
      <View style={styles.button}>
        <Button title={"add"} onPress={add} />
      </View>
      {/* Button to get data */}
      <View style={styles.button}>
        <Button title={"get"} onPress={get} />
      </View>
    </View>
  );
}

// Styles for the components
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  text: {
    fontSize: 40,
    marginBottom: 30,
  },
  button: {
    margin: 20,
    width: 250,
  },
});


Output: 



Next Article
Article Tags :

Similar Reads