0
0
React Nativemobile~5 mins

Why local data enables offline experience in React Native

Choose your learning style9 modes available
Introduction

Local data lets your app work even when there is no internet. It keeps important information saved on your device.

When users need to see their messages without internet.
When an app shows saved articles or notes offline.
When a game saves progress locally to play anytime.
When a shopping app keeps your cart data without connection.
When you want faster app loading by using stored data.
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');
AsyncStorage is a simple way to save key-value pairs on the device.
Use async/await to handle saving and reading data smoothly.
Examples
Save the username 'Alice' locally on the device.
React Native
await AsyncStorage.setItem('@username', 'Alice');
Retrieve the saved username to use in the app.
React Native
const username = await AsyncStorage.getItem('@username');
Delete the saved username from local storage.
React Native
await AsyncStorage.removeItem('@username');
Sample App

This app shows a message saved locally. When you press the button, it saves a message on your device. When the app starts, it loads the saved message so you can see it even without internet.

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

export default function OfflineExample() {
  const [message, setMessage] = useState('No message saved');

  const saveMessage = async () => {
    await AsyncStorage.setItem('@message', 'Hello offline world!');
    setMessage('Message saved locally');
  };

  const loadMessage = async () => {
    const saved = await AsyncStorage.getItem('@message');
    if (saved !== null) {
      setMessage(saved);
    } else {
      setMessage('No message found');
    }
  };

  useEffect(() => {
    loadMessage();
  }, []);

  return (
    <View style={{ padding: 20 }}>
      <Text>{message}</Text>
      <Button title="Save Message" onPress={saveMessage} />
    </View>
  );
}
OutputSuccess
Important Notes

Local data storage helps apps work offline and load faster.

Always handle errors when reading or writing local data.

Use local storage for small amounts of data like settings or messages.

Summary

Local data keeps app info on your device for offline use.

AsyncStorage in React Native is an easy way to save and read local data.

Offline experience improves user satisfaction and app reliability.