Bird
Raised Fist0
React Nativemobile~20 mins

Why local data enables offline experience in React Native - Build It to Prove It

Choose your learning style10 modes available
Build: Offline Notes
This screen lets users write and save notes locally on their device so they can access them even without internet.
Target UI
-------------------------
|      Offline Notes     |
|-----------------------|
| [Type your note here] |
|                       |
| [Save Note]           |
|-----------------------|
| Saved Notes:          |
| - Note 1              |
| - Note 2              |
|                       |
-------------------------
A TextInput to type a note
A Save button to store the note locally
A list showing all saved notes
Notes persist and show even if app restarts or device is offline
Starter Code
React Native
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Button, FlatList, StyleSheet } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

export default function OfflineNotes() {
  const [note, setNote] = useState('');
  const [notes, setNotes] = useState([]);

  useEffect(() => {
    // TODO: Load saved notes from local storage here
  }, []);

  const saveNote = async () => {
    // TODO: Save the new note locally and update the list
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Offline Notes</Text>
      <TextInput
        style={styles.input}
        placeholder="Type your note here"
        value={note}
        onChangeText={setNote}
      />
      <Button title="Save Note" onPress={saveNote} />
      <Text style={styles.subtitle}>Saved Notes:</Text>
      <FlatList
        data={notes}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item }) => <Text style={styles.noteItem}>- {item}</Text>}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20, backgroundColor: '#fff' },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 10 },
  input: { borderColor: '#ccc', borderWidth: 1, padding: 10, marginBottom: 10 },
  subtitle: { fontSize: 18, marginTop: 20, marginBottom: 10 },
  noteItem: { fontSize: 16, marginBottom: 5 }
});
Task 1
Task 2
Task 3
Solution
React Native
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Button, FlatList, StyleSheet } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

export default function OfflineNotes() {
  const [note, setNote] = useState('');
  const [notes, setNotes] = useState([]);

  useEffect(() => {
    const loadNotes = async () => {
      try {
        const savedNotes = await AsyncStorage.getItem('notes');
        if (savedNotes) {
          setNotes(JSON.parse(savedNotes));
        }
      } catch (e) {
        console.error('Failed to load notes.', e);
      }
    };
    loadNotes();
  }, []);

  const saveNote = async () => {
    if (note.trim() === '') return;
    const newNotes = [...notes, note.trim()];
    try {
      await AsyncStorage.setItem('notes', JSON.stringify(newNotes));
      setNotes(newNotes);
      setNote('');
    } catch (e) {
      console.error('Failed to save note.', e);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Offline Notes</Text>
      <TextInput
        style={styles.input}
        placeholder="Type your note here"
        value={note}
        onChangeText={setNote}
        accessibilityLabel="Note input field"
      />
      <Button title="Save Note" onPress={saveNote} accessibilityLabel="Save note button" />
      <Text style={styles.subtitle}>Saved Notes:</Text>
      <FlatList
        data={notes}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item }) => <Text style={styles.noteItem}>- {item}</Text>}
        accessibilityLabel="List of saved notes"
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20, backgroundColor: '#fff' },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 10 },
  input: { borderColor: '#ccc', borderWidth: 1, padding: 10, marginBottom: 10, borderRadius: 4 },
  subtitle: { fontSize: 18, marginTop: 20, marginBottom: 10 },
  noteItem: { fontSize: 16, marginBottom: 5 }
});

This app uses AsyncStorage to save notes locally on the device. When the app starts, it loads any saved notes from local storage so the user can see them even without internet.

When the user types a note and taps Save, the note is added to the list and saved back to AsyncStorage. This means the data stays on the device and is available offline.

We use React Native's useEffect to load notes once on mount, and useState to manage the notes list and input. Accessibility labels help screen readers identify inputs and buttons.

This approach shows how local data storage enables offline experience by keeping user data on the device.

Final Result
Completed Screen
-------------------------
|      Offline Notes     |
|-----------------------|
| [Type your note here] |
|                       |
| [Save Note]           |
|-----------------------|
| Saved Notes:          |
| - Buy groceries       |
| - Call mom            |
|                       |
-------------------------
User types a note in the input field
User taps 'Save Note' button
Note appears in the saved notes list below
Notes remain visible after app restart or offline
Stretch Goal
Add a button to clear all saved notes from local storage
💡 Hint
Use AsyncStorage.removeItem('notes') and update the notes state to an empty array

Practice

(1/5)
1. Why does storing data locally on a device help apps work offline?
easy
A. Because local data deletes itself when offline
B. Because local data automatically updates from the internet
C. Because the app stops working without internet
D. Because the app can access data without needing internet connection

Solution

  1. Step 1: Understand offline data storage

    Local data means the app saves information on the device itself, not on the internet.
  2. Step 2: Connect offline use to local data

    When offline, the app can still read saved data from the device, so it works without internet.
  3. Final Answer:

    Because the app can access data without needing internet connection -> Option D
  4. Quick Check:

    Offline access = local data usage [OK]
Hint: Offline means no internet, so local data is key [OK]
Common Mistakes:
  • Thinking local data updates automatically without internet
  • Believing app stops working offline
  • Confusing local data with temporary cache
2. Which of the following is the correct way to save a string value locally using AsyncStorage in React Native?
easy
A. await AsyncStorage.setItem('key', 'value');
B. AsyncStorage.save('key', 'value');
C. AsyncStorage.store('key', 'value');
D. await AsyncStorage.getItem('key', 'value');

Solution

  1. Step 1: Recall AsyncStorage method for saving data

    The correct method to save data is setItem with key and value as arguments.
  2. Step 2: Check syntax correctness

    Using await with AsyncStorage.setItem is correct because it returns a promise.
  3. Final Answer:

    await AsyncStorage.setItem('key', 'value'); -> Option A
  4. Quick Check:

    Save data = setItem with await [OK]
Hint: Remember setItem saves, getItem reads [OK]
Common Mistakes:
  • Using wrong method names like save or store
  • Using getItem to save data
  • Not using await with async calls
3. What will the following React Native code output if the device is offline but data was saved previously?
const value = await AsyncStorage.getItem('username');
console.log(value);
medium
A. null
B. The saved username string
C. An error because no internet
D. undefined

Solution

  1. Step 1: Understand AsyncStorage.getItem behavior

    AsyncStorage.getItem returns the saved value for the key if it exists locally.
  2. Step 2: Consider offline scenario

    Since data was saved before, it is available locally even without internet, so it returns the saved string.
  3. Final Answer:

    The saved username string -> Option B
  4. Quick Check:

    Offline + saved data = returned value [OK]
Hint: Offline does not block reading saved local data [OK]
Common Mistakes:
  • Assuming getItem returns null if offline
  • Expecting an error without internet
  • Confusing undefined with null
4. Identify the error in this React Native code snippet that tries to save data locally:
AsyncStorage.setItem('token', 12345);
medium
A. The value must be a string, not a number
B. The key must be a number, not a string
C. setItem is not an AsyncStorage method
D. Missing await keyword

Solution

  1. Step 1: Check AsyncStorage.setItem parameter types

    Both key and value must be strings when saving data with setItem.
  2. Step 2: Identify the incorrect value type

    The value 12345 is a number, so it should be converted to a string before saving.
  3. Final Answer:

    The value must be a string, not a number -> Option A
  4. Quick Check:

    setItem values must be strings [OK]
Hint: Always save strings with setItem [OK]
Common Mistakes:
  • Passing numbers directly without string conversion
  • Thinking key can be a number
  • Ignoring async/await usage
5. You want your React Native app to show a list of saved notes even when offline. Which approach best ensures this offline experience?
hard
A. Require internet to open the notes screen
B. Fetch notes from the server every time the app opens
C. Save notes locally using AsyncStorage when created or updated
D. Clear local data when offline to avoid stale info

Solution

  1. Step 1: Understand offline data needs

    To work offline, the app must have data saved locally on the device.
  2. Step 2: Choose the correct data handling method

    Saving notes locally with AsyncStorage when they change ensures they are available offline.
  3. Step 3: Evaluate other options

    Fetching from server requires internet, requiring internet blocks offline use, clearing data removes offline access.
  4. Final Answer:

    Save notes locally using AsyncStorage when created or updated -> Option C
  5. Quick Check:

    Offline access needs local saving [OK]
Hint: Save data locally on change for offline use [OK]
Common Mistakes:
  • Relying only on server fetches
  • Blocking offline screens
  • Deleting local data unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard