How To Use React Native AsyncStorage
Tags: javascript, data, react, mobile
Published: 2022-05-26 10:42:03

---
title: How To Use React Native AsyncStorage
published: true
description: Persisting data in mobile apps can be valuable to increase the user experience. In this post, we show how to implement this asynchronously in React Native.
tags: javascript, data, react, mobile
//cover_image: https://blog.jscrambler.com/content/images/2020/03/jscrambler-blog-how-to-use-react-native-asyncstorage.jpg
---

![react native asyncstorage](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b3f0aon361azndd6k7c6.jpg)

`AsyncStorage` is a simple, asynchronous, unencrypted by default module that allows you to persist data offline in React Native apps. The persistence of data is done in a key-value storage system.

There are numerous scenarios where this module can be beneficial. Persisting data in a mobile app has benefits such as when the user restarts the app, the data or the setting variables being available to the user in the state they left before closing the app. This scenario is going to be covered in this tutorial.

Find the complete code for this tutorial at this [GitHub repo](https://github.com/amawantndeepmittal/react-native-examples/tree/main/rnAsyncStorageExample). 

## Installing the community module

React Native version `0.60.0+` has lots of its API modules available as separate packages that you can easily install with a package manager such as npm or yarn. These packages are managed by community members as well as open-source developers.

To begin, let us create a new React Native project and install the module: [@react-native-async-storage/async-storage](https://react-native-async-storage.github.io/async-storage/docs/install/). From a terminal window, execute the following commands in the order they are specified.

```shell
# create a new react-native app
npx react-native init rnAsyncStorageExample

# navigate inside the project directory
cd rnAsyncStorageExample

# install the async-storage module
yarn add @react-native-async-storage/async-storage

# Or is you prefer to use npm
npm install @react-native-async-storage/async-storage
```

If you are using the latest React Native version (`0.60.x` or above) you do not have to link the native binaries for iOS and Android platforms manually. This linking of the module is handled automatically by the CLI. Though, for iOS, you have to install [cocoapods](https://cocoapods.org/). Go back to the terminal window and execute the following command:

```shell
npx pod-install ios
```

That's it in terms of configuring the AsyncStorage module to work in the React Native app.

## Changing the default storage limitation on Android

On iOS devices, the AsyncStorage is not limited programmatically.

On Android devices, by default, the current AsyncStorage size is set to `6MB`. Reaching this limit is going to result in errors like the database or disk being full. There are [valid reasons](https://react-native-async-storage.github.io/async-storage/docs/advanced/db_size/) why this limit exists but if there is a need to increase the size, you can do that. Open the `android/gradle.properties` file and add the following:

```java
AsyncStorage_db_size_in_MB=10
```

This file represents any project-wise settings that you can use to override the default values or settings.

Now, to make sure everything is working correctly, build the Android app (and make sure an Android device or emulator is running before you execute the command below).

```shell
npx react-native run-android
```

You are going to get the default screen that confirms that the app is configured.

<center><img src="https://blog.jscrambler.com/content/images/2020/03/jscrambler-blog-how-to-use-react-native-asyncstorage-1.png" alt="React Native AsyncStorage App 1" style="box-shadow: 0 4px 20px #7f7f7f;"></center>

Similarly, to build the app for iOS, execute the command below:

```shell
npx react-native run-ios
```

## Using the AsyncStorage API

Let's start creating an example. In this example application, you will save a value from the user's input in the storage and fetch the value from the storage. This reading and writing of data are going to be done with the help of AsyncStorage API functions.

Open the `App.js` file and start by importing the following components.

```js
import React, {useState, useEffect} from 'react';
import {
  StyleSheet,
  View,
  Text,
  TextInput,
  TouchableOpacity,
} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
```

Next, define a variable name `STORAGE_KEY`. It is used to read and save the data. You can think of this key as the identifier to the value that is being stored, hence, the key-value storage system. As you are going to store only one value at the moment, there is only one key required.

```js
let STORAGE_KEY = '@user_input';
```

Inside the functional component `App`, define a state variable `input` that has an empty string as its default value.

```js
const App = () => {
  const [input, setInput] = useState('');
  // ...
};

export default App;
```

## Saving the data

To save the data for the app to read, let us define an asynchronous helper method called `saveData`. This method is going to be promise-based, which means you can use the `async await` syntax with a `try-catch` block.

Passing the identifier `STORAGE_KEY` as well as the `input` state variable, the API method `AsyncStorage.setItem` is going to store the value in storage.

Let us update the state as well as display an alert box when the data is successfully stored.

```js
const saveData = async () => {
  try {
    await AsyncStorage.setItem(STORAGE_KEY, age)
    alert('Data successfully saved')
  } catch (e) {
    alert('Failed to save the data to the storage')
  }
}const saveData = async () => {
  try {
    await AsyncStorage.setItem(STORAGE_KEY, age)
    alert('Data successfully saved')
  } catch (e) {
    alert('Failed to save the data to the storage')
  }
}
```
<a href="https://blog.jscrambler.com/how-to-protect-react-native-apps-with-jscrambler/" target="_blank" class="protect-react-native-ad"><img alt="Protect your Code with Jscrambler" src="https://media.jscrambler.com/blog/V1-React%20Native.jpg"></a>

## Reading the data

When the app restarts, it should be able to read the data that persisted in the previous section. For this, create another helper function called `readData` that is going to be asynchronous. This function is going to read the value from the storage using the API method `AsyncStorage.getItem` and will only set the value of the state variable input when its value is not `null`.

```js
const readData = async () => {
  try {
    const value = await AsyncStorage.getItem(STORAGE_KEY);

    if (value !== null) {
      setInput(value);
    }
  } catch (e) {
    alert('Failed to fetch the input from storage');
  }
};
```

To retrieve the data whenever the app starts, invoke this method inside the `useEffect` hook.

```js
useEffect(() => {
  readData();
}, []);
```

## Clearing all storage

Another API method that the current demo app is going to utilize from the AsyncStorage API is called `clear`. This method deletes everything that was previously saved.

If you want to delete only a specific item from the storage, there are other methods available such as `removeItem` or `multiRemove` by the AsyncStorage API.

Add the following snippet:

```js
const clearStorage = async () => {
  try {
    await AsyncStorage.clear();
    alert('Storage successfully cleared!');
  } catch (e) {
    alert('Failed to clear the async storage.');
  }
};
```

## Controlling the input

The last two helper functions this example app requires are `onChangeText` and `onSubmitEditing`.

These methods are going to be responsible for reading the input and updating the state variable as well as storing the input.

```js
const onChangeText = value => setInput(value);

const onSubmitEditing = () => {
  if (!input) return;

  saveData(input);
  setInput('');
};
```

## Completing the app

We have defined all the helper functions that are required by the app. Let us complete the `return` statement by defining the JSX as below:

```js
const App = () => {
  // ... rest of the code remains the same

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.title}>AsyncStorage React Native</Text>
      </View>
      <View style={styles.panel}>
        <Text style={styles.label}>Enter your input here:</Text>
        <TextInput
          style={styles.inputField}
          value={input}
          placeholder="Enter"
          onChangeText={onChangeText}
          onSubmitEditing={onSubmitEditing}
        />
        <Text style={styles.text}>Your input is {input}</Text>
        <Pressable onPress={clearStorage} style={styles.button}>
          <Text style={styles.buttonText}>Clear Storage</Text>
        </Pressable>
      </View>
    </View>
  );
};
```

Here are the corresponding styles to the above code snippet:

```js
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    width: '100%',
    backgroundColor: '#dcdcdc',
    paddingTop: 48,
    paddingBottom: 10,
    borderBottomWidth: StyleSheet.hairlineWidth,
    alignItems: 'center',
  },
  title: {
    fontSize: 22,
    color: '#333',
    fontWeight: 'bold',
  },
  panel: {
    paddingTop: 10,
    paddingHorizontal: 10,
  },
  label: {
    fontSize: 20,
  },
  text: {
    fontSize: 24,
    paddingTop: 10,
  },
  inputField: {
    backgroundColor: '#fff',
    height: 44,
    borderWidth: 1,
    borderColor: '#333',
    width: '100%',
    padding: 10,
    marginTop: 12,
  },
  button: {
    margin: 10,
    padding: 10,
    backgroundColor: 'orange',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 4,
  },
  buttonText: {
    fontSize: 18,
    color: '#444',
  },
});
```

Now, go back to the iOS simulator and you are going to be welcomed by the following screen:

<center><img src="https://blog.jscrambler.com/content/images/2022/05/jscrambler-blog-asyncstorage-1.gif"></center>

Next, enter a value, close the app, and then open the app to see if the value was stored or not.

<center><img src="https://blog.jscrambler.com/content/images/2022/05/jscrambler-blog-asyncstorage-2.gif"></center>

Lastly, see what happens when you click on the "Clear Storage" button.

<center><img src="https://blog.jscrambler.com/content/images/2022/05/jscrambler-blog-asyncstorage-3.png"></center>

## Conclusion

Congratulations! I hope that, in this tutorial, you learned the basic API methods of using AsyncStorage API in your React Native app. Even though the demo app was minimal, it allowed us to understand the concepts.

Here is the [link](https://react-native-async-storage.github.io/async-storage/docs/api) to the complete API for the `AsyncStorage` module that you can refer to for further reading.

And speaking of further reading, don't miss our guide on [React Native Security](https://blog.jscrambler.com/securing-react-native-applications/?utm_source=dev.to&utm_medium=referral&utm_campaign=react-native-asyncstorage) and <a href="https://blog.jscrambler.com/how-to-protect-react-native-apps-with-jscrambler/?utm_source=dev.to&utm_medium=referral&utm_campaign=react-native-asyncstorage" target="_blank" class="protect-react-native-link">our tutorial</a> on protecting the source code of React Native apps against code tampering and reverse-engineering.