0
0
React Nativemobile~5 mins

AsyncStorage for key-value in React Native

Choose your learning style9 modes available
Introduction

AsyncStorage lets you save small pieces of data on the phone. This helps keep information even after the app closes.

Save user preferences like theme or language
Store a login token to keep the user signed in
Remember if a tutorial was already shown
Cache small data to load faster next time
Syntax
React Native
import AsyncStorage from '@react-native-async-storage/async-storage';

// Save data
await AsyncStorage.setItem('key', 'value');

// Read data
const value = await AsyncStorage.getItem('key');

// Remove data
await AsyncStorage.removeItem('key');
AsyncStorage methods are asynchronous and return Promises.
Always use try-catch to handle errors when reading or writing.
Examples
Save the string 'Alice' under the key 'username'.
React Native
await AsyncStorage.setItem('username', 'Alice');
Retrieve the value saved with key 'username'.
React Native
const username = await AsyncStorage.getItem('username');
Delete the saved value for 'username'.
React Native
await AsyncStorage.removeItem('username');
Sample App

This app lets you type your name and save it on the phone. When you open the app again, it shows the saved name.

React Native
import React, { useState, useEffect } from 'react';
import { View, Text, Button, TextInput } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

export default function App() {
  const [name, setName] = useState('');
  const [storedName, setStoredName] = useState('');

  useEffect(() => {
    async function loadName() {
      try {
        const value = await AsyncStorage.getItem('name');
        if (value !== null) {
          setStoredName(value);
        }
      } catch (e) {
        // error reading value
      }
    }
    loadName();
  }, []);

  const saveName = async () => {
    try {
      await AsyncStorage.setItem('name', name);
      setStoredName(name);
      setName('');
    } catch (e) {
      // saving error
    }
  };

  return (
    <View style={{ padding: 20 }}>
      <Text>Enter your name:</Text>
      <TextInput
        value={name}
        onChangeText={setName}
        placeholder="Your name"
        style={{ borderWidth: 1, marginVertical: 10, padding: 5 }}
      />
      <Button title="Save Name" onPress={saveName} />
      {storedName ? <Text style={{ marginTop: 20 }}>Saved name: {storedName}</Text> : null}
    </View>
  );
}
OutputSuccess
Important Notes

AsyncStorage is good for small data only, not big files or databases.

Always handle errors to avoid app crashes.

Data saved is persistent until removed or app is uninstalled.

Summary

AsyncStorage stores key-value pairs on the device.

Use async/await to save, read, and remove data.

Great for saving user settings and small info.