------------------------- | Fast Storage Demo | |-----------------------| | Enter text: | | [______________] | | | | [Save] [Load] | | | | Saved value: | | [ ] | -------------------------
MMKV for fast storage in React Native - Mini App: Build & Ship
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' } });
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.
------------------------- | Fast Storage Demo | |-----------------------| | Enter text: | | [Hello MMKV ] | | | | [Save] [Load] | | | | Saved value: | | [Hello MMKV ] | -------------------------
Practice
MMKV in a React Native app?Solution
Step 1: Understand MMKV's role
MMKV is designed for fast storage of small data in apps.Step 2: Compare options
Options A, B, and C relate to app layouts, animations, and networking, which are not MMKV's purpose.Final Answer:
To store small data quickly and keep it after app closes -> Option BQuick Check:
MMKV = fast persistent storage [OK]
- Confusing MMKV with UI or animation libraries
- Thinking MMKV handles network calls
- Assuming MMKV is for large file storage
Solution
Step 1: Recall MMKV save method
The correct method to save data isset.Step 2: Check other options
Methods likesave,store, andputare not valid MMKV methods.Final Answer:
MMKV.set('key', 'value') -> Option AQuick Check:
Use set() to save data [OK]
- Using incorrect method names like save or put
- Confusing MMKV with AsyncStorage syntax
- Forgetting to pass both key and value
const MMKV = require('react-native-mmkv').MMKV;
const storage = new MMKV();
storage.set('name', 'Alice');
const result = storage.getString('name');
console.log(result);Solution
Step 1: Analyze storage.set call
The code saves the string 'Alice' with key 'name'.Step 2: Analyze storage.getString call
Retrieves the string stored under 'name', which is 'Alice'.Final Answer:
'Alice' -> Option CQuick Check:
getString('name') returns 'Alice' [OK]
- Expecting undefined if not awaited
- Confusing getString with get() method
- Assuming getString returns null if key exists
const storage = new MMKV();
storage.set('count', 5);
const value = storage.getString('count');
console.log(value);Solution
Step 1: Check data type saved
The code saves a number 5 using set.Step 2: Check retrieval method
getString expects a string value, but 'count' stores a number, causing mismatch.Final Answer:
Using getString to read a number value -> Option AQuick Check:
getString expects string data [OK]
- Trying to getString for non-string data
- Assuming set is async and needs await
- Thinking MMKV constructor needs arguments
Solution
Step 1: Save theme preference correctly
Usesetto save the string 'dark' under 'theme'.Step 2: Retrieve with fallback
UsegetString('theme')and fallback to 'dark' if null or undefined using??.Final Answer:
const storage = new MMKV(); storage.set('theme', 'dark'); const theme = storage.getString('theme') ?? 'dark'; -> Option DQuick Check:
Use set() and getString() with nullish fallback [OK]
- Using non-existent save() method
- Not providing fallback value on getString
- Using get() instead of getString for strings
Ready to prove it?
Pass the test and this pattern moves unknown
