Bird
Raised Fist0
React Nativemobile~20 mins

MMKV for fast storage in React Native - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Fast Storage Demo
This screen lets users save and load a simple text value quickly using MMKV storage.
Target UI
-------------------------
| Fast Storage Demo     |
|-----------------------|
| Enter text:           |
| [______________]      |
|                       |
| [Save]    [Load]      |
|                       |
| Saved value:          |
| [                 ]   |
-------------------------
Use MMKV storage to save a text string when Save button is pressed
Load and display the saved text when Load button is pressed
Use a TextInput for user input
Show the saved value below buttons
Handle empty input gracefully
Starter Code
React Native
import React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet } from 'react-native';
import { MMKV } from 'react-native-mmkv';

const storage = new MMKV();

export default function FastStorageDemo() {
  const [input, setInput] = useState('');
  const [savedValue, setSavedValue] = useState('');

  // TODO: Add save function

  // TODO: Add load function

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Fast Storage Demo</Text>
      <Text>Enter text:</Text>
      <TextInput
        style={styles.input}
        value={input}
        onChangeText={setInput}
        placeholder="Type something"
        accessibilityLabel="Input text field"
      />
      <View style={styles.buttonRow}>
        <Button title="Save" onPress={() => {}} />
        <Button title="Load" onPress={() => {}} />
      </View>
      <Text>Saved value:</Text>
      <Text style={styles.savedValue}>{savedValue}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { padding: 20, flex: 1, justifyContent: 'flex-start' },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20 },
  input: { borderWidth: 1, borderColor: '#ccc', padding: 10, marginVertical: 10, borderRadius: 5 },
  buttonRow: { flexDirection: 'row', justifyContent: 'space-between', marginVertical: 10 },
  savedValue: { fontSize: 18, marginTop: 10, color: '#333' }
});
Task 1
Task 2
Task 3
Solution
React Native
import React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet } from 'react-native';
import { MMKV } from 'react-native-mmkv';

const storage = new MMKV();

export default function FastStorageDemo() {
  const [input, setInput] = useState('');
  const [savedValue, setSavedValue] = useState('');

  const saveValue = () => {
    if (input.trim() === '') {
      alert('Please enter some text to save.');
      return;
    }
    storage.set('myKey', input);
    alert('Value saved!');
  };

  const loadValue = () => {
    const value = storage.getString('myKey');
    if (value === undefined) {
      alert('No value found. Please save something first.');
      setSavedValue('');
    } else {
      setSavedValue(value);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Fast Storage Demo</Text>
      <Text>Enter text:</Text>
      <TextInput
        style={styles.input}
        value={input}
        onChangeText={setInput}
        placeholder="Type something"
        accessibilityLabel="Input text field"
      />
      <View style={styles.buttonRow}>
        <Button title="Save" onPress={saveValue} />
        <Button title="Load" onPress={loadValue} />
      </View>
      <Text>Saved value:</Text>
      <Text style={styles.savedValue}>{savedValue}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { padding: 20, flex: 1, justifyContent: 'flex-start' },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20 },
  input: { borderWidth: 1, borderColor: '#ccc', padding: 10, marginVertical: 10, borderRadius: 5 },
  buttonRow: { flexDirection: 'row', justifyContent: 'space-between', marginVertical: 10 },
  savedValue: { fontSize: 18, marginTop: 10, color: '#333' }
});

We created two functions: saveValue and loadValue. The saveValue function checks if the input is not empty, then saves it to MMKV storage with the key myKey. It shows an alert to confirm saving.

The loadValue function tries to get the stored string from MMKV. If nothing is found, it alerts the user and clears the displayed saved value. Otherwise, it updates the savedValue state to show the stored text.

These functions are connected to the Save and Load buttons respectively. The UI updates immediately when loading the saved value.

This example shows how MMKV provides a fast and simple way to store small pieces of data persistently in React Native apps.

Final Result
Completed Screen
-------------------------
| Fast Storage Demo     |
|-----------------------|
| Enter text:           |
| [Hello MMKV    ]      |
|                       |
| [Save]    [Load]      |
|                       |
| Saved value:          |
| [Hello MMKV    ]      |
-------------------------
User types text in the input field
Tapping Save stores the text in MMKV and shows a confirmation alert
Tapping Load retrieves the saved text and displays it below
If input is empty on Save, an alert asks to enter text
If no saved value exists on Load, an alert informs the user
Stretch Goal
Add a Clear button to remove the saved value from MMKV and clear the displayed saved value.
💡 Hint
Use storage.delete('myKey') to remove the key and update savedValue state to empty string.

Practice

(1/5)
1. What is the main purpose of using MMKV in a React Native app?
easy
A. To design app layouts
B. To store small data quickly and keep it after app closes
C. To handle network requests
D. To create complex animations

Solution

  1. Step 1: Understand MMKV's role

    MMKV is designed for fast storage of small data in apps.
  2. Step 2: Compare options

    Options A, B, and C relate to app layouts, animations, and networking, which are not MMKV's purpose.
  3. Final Answer:

    To store small data quickly and keep it after app closes -> Option B
  4. Quick Check:

    MMKV = fast persistent storage [OK]
Hint: MMKV is for fast data storage, not UI or network [OK]
Common Mistakes:
  • Confusing MMKV with UI or animation libraries
  • Thinking MMKV handles network calls
  • Assuming MMKV is for large file storage
2. Which of the following is the correct way to save a string value using MMKV in React Native?
easy
A. MMKV.set('key', 'value')
B. MMKV.save('key', 'value')
C. MMKV.store('key', 'value')
D. MMKV.put('key', 'value')

Solution

  1. Step 1: Recall MMKV save method

    The correct method to save data is set.
  2. Step 2: Check other options

    Methods like save, store, and put are not valid MMKV methods.
  3. Final Answer:

    MMKV.set('key', 'value') -> Option A
  4. Quick Check:

    Use set() to save data [OK]
Hint: Use set() to save data in MMKV [OK]
Common Mistakes:
  • Using incorrect method names like save or put
  • Confusing MMKV with AsyncStorage syntax
  • Forgetting to pass both key and value
3. What will be the output of this code snippet?
const MMKV = require('react-native-mmkv').MMKV;
const storage = new MMKV();
storage.set('name', 'Alice');
const result = storage.getString('name');
console.log(result);
medium
A. undefined
B. null
C. 'Alice'
D. Error: getString is not a function

Solution

  1. Step 1: Analyze storage.set call

    The code saves the string 'Alice' with key 'name'.
  2. Step 2: Analyze storage.getString call

    Retrieves the string stored under 'name', which is 'Alice'.
  3. Final Answer:

    'Alice' -> Option C
  4. Quick Check:

    getString('name') returns 'Alice' [OK]
Hint: getString returns saved string value [OK]
Common Mistakes:
  • Expecting undefined if not awaited
  • Confusing getString with get() method
  • Assuming getString returns null if key exists
4. Identify the error in this MMKV usage code:
const storage = new MMKV();
storage.set('count', 5);
const value = storage.getString('count');
console.log(value);
medium
A. Using getString to read a number value
B. Missing await before storage.set
C. MMKV constructor requires parameters
D. set method only accepts strings

Solution

  1. Step 1: Check data type saved

    The code saves a number 5 using set.
  2. Step 2: Check retrieval method

    getString expects a string value, but 'count' stores a number, causing mismatch.
  3. Final Answer:

    Using getString to read a number value -> Option A
  4. Quick Check:

    getString expects string data [OK]
Hint: Match getString with string data only [OK]
Common Mistakes:
  • Trying to getString for non-string data
  • Assuming set is async and needs await
  • Thinking MMKV constructor needs arguments
5. You want to save a user's theme preference ('dark' or 'light') and retrieve it safely after app restart using MMKV. Which code snippet correctly does this?
hard
A. const storage = new MMKV(); storage.set('theme', 'dark'); const theme = storage.getString('theme');
B. const storage = new MMKV(); storage.set('theme', 'dark'); const theme = storage.get('theme');
C. const storage = new MMKV(); storage.save('theme', 'dark'); const theme = storage.getString('theme');
D. const storage = new MMKV(); storage.set('theme', 'dark'); const theme = storage.getString('theme') ?? 'dark';

Solution

  1. Step 1: Save theme preference correctly

    Use set to save the string 'dark' under 'theme'.
  2. Step 2: Retrieve with fallback

    Use getString('theme') and fallback to 'dark' if null or undefined using ??.
  3. Final Answer:

    const storage = new MMKV(); storage.set('theme', 'dark'); const theme = storage.getString('theme') ?? 'dark'; -> Option D
  4. Quick Check:

    Use set() and getString() with nullish fallback [OK]
Hint: Use ?? for safe fallback when reading MMKV data [OK]
Common Mistakes:
  • Using non-existent save() method
  • Not providing fallback value on getString
  • Using get() instead of getString for strings
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