Mobile development · Intermediate · 20 min
Save settings fast in React Native with MMKV
By Padding · Updated 18 Nov 2026
Expo SDK 58 · react-native-mmkv 4.3.2 · Node.js 26 (node:26)
You will have an Expo SDK 58 app that keeps its theme, onboarding flag and text size in MMKV, with a per-account store, a one-off move from AsyncStorage and Jest tests for all of it.
On this page
Most apps have a handful of small choices to remember: the colour theme, whether the person has seen the welcome screens, the text size they picked, the tab they were on. Saving them should not slow the app down, and reading them should not need a loading state. MMKV is a key-value store written in C++ that reads and writes synchronously, so the app knows the theme before it draws the first screen. That matters most on low-cost Android phones, where an asynchronous read at start-up shows as a flash of the wrong theme.
You will add react-native-mmkv 4.3 to an Expo SDK 58 app, generate the Android project to see the native module land, and build a small typed settings layer on top of it: getters that never return a value of the wrong type, a hook that keeps a theme picker in step with storage, one store per signed-in account, and a migration that moves old values out of AsyncStorage exactly once. Everything is covered by Jest tests that run on your computer.
Step 1 · Decide what belongs in MMKV
MMKV stores strings, numbers, booleans and binary buffers under string keys, in a file in the app's private folder. It has no queries, no relations and no transactions across keys. Before installing anything, sort the data your app keeps.
Good fits for MMKV:
- the theme (
system,lightordark) - whether onboarding has been seen
- the text size the person chose
- the last tab or filter they used
- the interface language, if your app lets people pick one that differs from the phone's
Poor fits:
- lists of records you sort or filter, such as appointments or messages. Put them in SQLite, where you can query them; see storing appointments with expo-sqlite.
- sign-in tokens, passwords and API keys. MMKV writes values in plain text by default. They belong in the iOS Keychain or the Android Keystore, through expo-secure-store.
- large blobs such as images. Keep them as files and store only the path.
Check it worked
Write down the keys your app will keep in MMKV. Each one should be a single small value you can describe in a few words. If any is a token, a password or a growing list, move it to the store named above before you continue.
Step 2 · Install MMKV and generate the native project
Create a throwaway app to work in. When it asks to download create-expo-app, answer y:
cd ~
npx create-expo-app@5.0.0 mmkv-settings-demoVersion 4 of react-native-mmkv is built on Nitro Modules, so it needs react-native-nitro-modules alongside it. Neither package is part of the Expo SDK, so pin the versions yourself:
cd ~/mmkv-settings-demo
npx expo install react-native-mmkv@4.3.2 react-native-nitro-modules@0.37.2MMKV has native code, and Expo Go only contains the native modules that ship with the Expo SDK. If you open this app in Expo Go after adding MMKV, it fails when it first creates a store. You need a development build: your own build of the app that includes the module. Prebuild generates the android (and ios) project that such a build compiles.
Prebuild needs an Android package name. Set one in app.json (replace com.example.mmkvsettings with your own reverse-domain name), then generate the Android project without installing anything else:
cd ~/mmkv-settings-demo
node -e "const fs=require('fs');const c=JSON.parse(fs.readFileSync('app.json','utf8'));c.expo.android.package='com.example.mmkvsettings';fs.writeFileSync('app.json',JSON.stringify(c,null,2)+'\n')"
npx expo prebuild --platform android --no-installTo run it on an emulator or an Android phone with USB debugging on, use npx expo run:android, which needs Android Studio and its SDK. On a Mac, npx expo run:ios does the same for the iOS Simulator. EAS Build can make the same development build in the cloud if you would rather not install either.
npx expo run:androidCheck it worked
Ask Expo's autolinking which native libraries the Android build will include:
cd ~/mmkv-settings-demo
ls android
npx expo-modules-autolinking react-native-config --platform android --json > /tmp/autolinking.json
node -e "const d=require('/tmp/autolinking.json').dependencies; console.log(Object.keys(d).filter(n => /mmkv|nitro/.test(n)).join(' '))"The listing shows app, build.gradle, settings.gradle and the Gradle wrapper files, and the last line prints react-native-mmkv react-native-nitro-modules. Gradle links both into the app when it builds.
Step 3 · Write a typed settings module
createMMKV returns a store. Give it an id so its file is separate from any other store, create it once at module level, and import it wherever you need it. Every MMKV getter returns undefined when the key is missing or holds a different type, so wrap each setting in a small function that returns a sensible default and rejects values it does not recognise. An older version of your app, or a bug, could have written anything.
cd ~/mmkv-settings-demo
mkdir -p src/storage
cat > src/storage/settings.ts <<'TS'
import { createMMKV } from 'react-native-mmkv'
// One instance for app-wide preferences, stored in its own file called "settings".
// Create it once and import it everywhere: never call createMMKV inside a component.
export const settings = createMMKV({ id: 'settings' })
export const KEYS = {
theme: 'theme',
onboardingSeen: 'onboarding.seen',
lastTab: 'nav.lastTab',
textScale: 'text.scale',
} as const
export type ThemeChoice = 'system' | 'light' | 'dark'
export const THEME_CHOICES: readonly ThemeChoice[] = ['system', 'light', 'dark']
export function isThemeChoice(value: unknown): value is ThemeChoice {
return typeof value === 'string' && (THEME_CHOICES as readonly string[]).includes(value)
}
// A value written by an older version of the app, or by hand, falls back to the default.
export function getTheme(): ThemeChoice {
const value = settings.getString(KEYS.theme)
return isThemeChoice(value) ? value : 'system'
}
export function setTheme(value: ThemeChoice): void {
settings.set(KEYS.theme, value)
}
export function hasSeenOnboarding(): boolean {
return settings.getBoolean(KEYS.onboardingSeen) ?? false
}
export function markOnboardingSeen(): void {
settings.set(KEYS.onboardingSeen, true)
}
export const TEXT_SCALE_MIN = 0.85
export const TEXT_SCALE_MAX = 1.6
export function getTextScale(): number {
const value = settings.getNumber(KEYS.textScale)
return value !== undefined && value >= TEXT_SCALE_MIN && value <= TEXT_SCALE_MAX ? value : 1
}
export function setTextScale(value: number): void {
if (!(value >= TEXT_SCALE_MIN && value <= TEXT_SCALE_MAX)) {
throw new RangeError(`Text scale must be between ${TEXT_SCALE_MIN} and ${TEXT_SCALE_MAX}`)
}
settings.set(KEYS.textScale, value)
}
export function getLastTab(): string | undefined {
return settings.getString(KEYS.lastTab)
}
export function setLastTab(name: string): void {
settings.set(KEYS.lastTab, name)
}
TSThe keys live in one KEYS object, so a typo becomes a TypeScript error instead of a setting that silently never loads. Values keep their type: set('onboarding.seen', true) stores a boolean, and getString on that key returns undefined, not "true". That is the main difference from AsyncStorage, where everything is a string.
Check it worked
cd ~/mmkv-settings-demo
grep -c "export function" src/storage/settings.tsThe count is 9: the type guard and eight getters and setters.
Step 4 · Test the settings under Jest
Under Jest, react-native-mmkv notices the test run and hands back an in-memory store instead of the native one, so createMMKV works unchanged in tests. The package still imports react-native-nitro-modules, though, and that package looks for its native half as soon as it is loaded. A one-line stub in a Jest setup file stops that; the in-memory store never calls into it.
Install Jest with the Expo preset and React Native Testing Library, then point Jest at the setup file:
cd ~/mmkv-settings-demo
npx expo install --dev jest-expo jest @types/jest
npm install --save-dev @testing-library/react-native@14.1.0 test-renderer@1.3.1
cat > jest.setup.ts <<'TS'
// react-native-mmkv uses its own in-memory store under Jest. This stub only stops
// react-native-nitro-modules from looking for native code when it is imported.
jest.mock('react-native-nitro-modules', () => ({ NitroModules: {} }))
TS
npm pkg set jest.preset=jest-expo 'jest.setupFiles[0]=<rootDir>/jest.setup.ts' scripts.test=jestNow test the defaults, the types and the fallbacks. clearAll before each test gives every test an empty store:
cd ~/mmkv-settings-demo
cat > src/storage/settings.test.ts <<'TS'
import {
getTextScale,
getTheme,
hasSeenOnboarding,
KEYS,
markOnboardingSeen,
setTextScale,
setTheme,
settings,
} from './settings'
beforeEach(() => {
settings.clearAll()
})
test('returns the defaults on first launch', () => {
expect(getTheme()).toBe('system')
expect(hasSeenOnboarding()).toBe(false)
expect(getTextScale()).toBe(1)
})
test('keeps each value with its own type', () => {
setTheme('dark')
markOnboardingSeen()
setTextScale(1.25)
expect(getTheme()).toBe('dark')
expect(settings.getBoolean(KEYS.onboardingSeen)).toBe(true)
expect(settings.getString(KEYS.onboardingSeen)).toBeUndefined()
expect(getTextScale()).toBe(1.25)
})
test('falls back to the default for a value it does not recognise', () => {
settings.set(KEYS.theme, 'sepia')
settings.set(KEYS.textScale, 9)
expect(getTheme()).toBe('system')
expect(getTextScale()).toBe(1)
})
test('refuses a text scale outside the range', () => {
expect(() => setTextScale(3)).toThrow(RangeError)
expect(settings.contains(KEYS.textScale)).toBe(false)
})
TS
npx jest src/storage/settings --ciCheck it worked
Jest reports Tests: 4 passed, 4 total. To see a test catch a real mistake, change the default in getTheme from 'system' to 'light' and run npx jest src/storage/settings again: the first and third tests fail. Change it back before you continue.
Step 5 · Bind a theme picker to storage with useMMKVString
useMMKVString(key, store) reads a key and re-renders the component whenever that key changes, wherever the change came from. Wrap it in a hook that applies the same validation as getTheme, so the screen never sees an unknown value:
cd ~/mmkv-settings-demo
cat > src/storage/use-theme-choice.ts <<'TS'
import { useMMKVString } from 'react-native-mmkv'
import { isThemeChoice, KEYS, settings, type ThemeChoice } from './settings'
// Re-renders the component whenever the theme key changes, from any screen.
export function useThemeChoice(): [ThemeChoice, (value: ThemeChoice) => void] {
const [raw, setRaw] = useMMKVString(KEYS.theme, settings)
const theme = isThemeChoice(raw) ? raw : 'system'
return [theme, setRaw]
}
TS
cat > src/components/theme-picker.tsx <<'TSX'
import { Pressable, StyleSheet, Text, useColorScheme, View } from 'react-native'
import { THEME_CHOICES, type ThemeChoice } from '@/storage/settings'
import { useThemeChoice } from '@/storage/use-theme-choice'
const LABELS: Record<ThemeChoice, string> = {
system: 'Match the phone',
light: 'Light',
dark: 'Dark',
}
// The same text and secondary colours as the template's src/constants/theme.ts.
const COLOURS = {
light: { text: '#000000', border: '#60646C' },
dark: { text: '#ffffff', border: '#B0B4BA' },
} as const
export function ThemePicker() {
const [theme, setTheme] = useThemeChoice()
const colours = COLOURS[useColorScheme() === 'dark' ? 'dark' : 'light']
return (
<View accessibilityRole="radiogroup" accessibilityLabel="Theme" style={styles.group}>
{THEME_CHOICES.map((choice) => (
<Pressable
key={choice}
accessibilityRole="radio"
accessibilityState={{ checked: theme === choice }}
onPress={() => setTheme(choice)}
style={[styles.option, { borderColor: colours.border }, theme === choice && styles.selected]}
>
<Text style={{ color: colours.text }}>{LABELS[choice]}</Text>
</Pressable>
))}
</View>
)
}
const styles = StyleSheet.create({
group: { gap: 8, padding: 16 },
option: { minHeight: 48, justifyContent: 'center', paddingHorizontal: 16, borderWidth: 1, borderRadius: 8 },
selected: { borderWidth: 3 },
})
TSX
cat > src/app/settings.tsx <<'TSX'
import { SafeAreaView } from 'react-native-safe-area-context'
import { ThemePicker } from '@/components/theme-picker'
import { useTheme } from '@/hooks/use-theme'
export default function SettingsScreen() {
const colors = useTheme()
return (
<SafeAreaView style={{ flex: 1, backgroundColor: colors.background }}>
<ThemePicker />
</SafeAreaView>
)
}
TSXThe labels and borders take their colours from the current scheme, so they stay readable the moment someone picks Dark. Each option is a radio button with its checked state exposed. TalkBack reads something like "Dark, radio button, not checked". VoiceOver has no radio button trait, so it reads the label and the selected state in its own words. Each option is at least 48 points tall, which is big enough for a thumb. The selected option also gets a thicker border, so the choice does not rely on colour alone.
The template's tabs are declared in src/components/app-tabs.tsx, and a screen file with no tab trigger has no way in from the interface. Replace that file with one that adds a Settings tab after Home and Explore (it reuses the Explore icon; swap in your own later):
cd ~/mmkv-settings-demo
cat > src/components/app-tabs.tsx <<'TSX'
import { NativeTabs } from 'expo-router/native-tabs'
import { useColorScheme } from 'react-native'
import { Colors } from '@/constants/theme'
export default function AppTabs() {
const scheme = useColorScheme()
const colors = Colors[scheme === 'dark' ? 'dark' : 'light']
return (
<NativeTabs
backgroundColor={colors.background}
indicatorColor={colors.backgroundElement}
labelStyle={{ selected: { color: colors.text } }}>
<NativeTabs.Trigger name="index">
<NativeTabs.Trigger.Label>Home</NativeTabs.Trigger.Label>
<NativeTabs.Trigger.Icon
src={require('@/assets/images/tabIcons/home.png')}
renderingMode="template"
/>
</NativeTabs.Trigger>
<NativeTabs.Trigger name="explore">
<NativeTabs.Trigger.Label>Explore</NativeTabs.Trigger.Label>
<NativeTabs.Trigger.Icon
src={require('@/assets/images/tabIcons/explore.png')}
renderingMode="template"
/>
</NativeTabs.Trigger>
<NativeTabs.Trigger name="settings">
<NativeTabs.Trigger.Label>Settings</NativeTabs.Trigger.Label>
<NativeTabs.Trigger.Icon
src={require('@/assets/images/tabIcons/explore.png')}
renderingMode="template"
/>
</NativeTabs.Trigger>
</NativeTabs>
)
}
TSXNow make the whole app follow the choice. The template's screens, its themed text and views, and the tab bar all call useColorScheme(), which reports the phone's setting. Changing only the navigation theme would leave them light. Instead, pass the stored choice to Appearance.setColorScheme, which overrides the scheme for the whole app: light or dark forces it, and auto goes back to following the phone. Every useColorScheme() call then returns the person's choice. Put that in a small helper:
cd ~/mmkv-settings-demo
cat > src/storage/apply-theme.ts <<'TS'
import { Appearance } from 'react-native'
import type { ThemeChoice } from './settings'
// Overrides the colour scheme for the whole app. 'auto' follows the phone again.
export function applyTheme(choice: ThemeChoice): void {
Appearance.setColorScheme(choice === 'system' ? 'auto' : choice)
}
TSThen replace the template's root layout with one that applies the stored theme before the first render, applies it again whenever the choice changes, and keeps the template's tabs and splash overlay:
cd ~/mmkv-settings-demo
cat > src/app/_layout.tsx <<'TSX'
import { DarkTheme, DefaultTheme, ThemeProvider } from 'expo-router'
import * as SplashScreen from 'expo-splash-screen'
import { useEffect } from 'react'
import { useColorScheme } from 'react-native'
import { AnimatedSplashOverlay } from '@/components/animated-icon'
import AppTabs from '@/components/app-tabs'
import { applyTheme } from '@/storage/apply-theme'
import { getTheme } from '@/storage/settings'
import { useThemeChoice } from '@/storage/use-theme-choice'
SplashScreen.preventAutoHideAsync()
// MMKV reads synchronously, so the saved theme is applied before anything renders.
applyTheme(getTheme())
export default function RootLayout() {
const [choice] = useThemeChoice()
const scheme = useColorScheme()
useEffect(() => {
applyTheme(choice)
}, [choice])
return (
<ThemeProvider value={scheme === 'dark' ? DarkTheme : DefaultTheme}>
<AnimatedSplashOverlay />
<AppTabs />
</ThemeProvider>
)
}
TSXBecause MMKV reads synchronously, the override is in place before the first render, so the first screen the app draws already uses the saved theme. There is no "loading settings" state to design.
Test the picker the way a person uses it, and check that it also follows a change made elsewhere in the app:
cd ~/mmkv-settings-demo
cat > src/components/theme-picker.test.tsx <<'TSX'
import { act, render, screen, userEvent } from '@testing-library/react-native'
import { getTheme, settings } from '@/storage/settings'
import { ThemePicker } from './theme-picker'
beforeEach(() => {
settings.clearAll()
})
test('starts on Match the phone and saves the choice', async () => {
const user = userEvent.setup()
await render(<ThemePicker />)
expect(screen.getByRole('radio', { name: 'Match the phone' })).toBeChecked()
await user.press(screen.getByRole('radio', { name: 'Dark' }))
expect(screen.getByRole('radio', { name: 'Dark' })).toBeChecked()
expect(screen.getByRole('radio', { name: 'Match the phone' })).not.toBeChecked()
expect(getTheme()).toBe('dark')
})
test('updates when another part of the app changes the setting', async () => {
await render(<ThemePicker />)
await act(async () => {
settings.set('theme', 'light')
})
expect(screen.getByRole('radio', { name: 'Light' })).toBeChecked()
})
TSX
npx jest src/components/theme-picker --ciCheck it worked
Jest reports Tests: 2 passed, 2 total. On a development build, a third tab called Settings sits after Home and Explore. Open it and pick Dark: the Settings screen, the Home and Explore screens and the tab bar all turn dark, whatever the phone is set to. Pick Match the phone and they follow the phone again. Pick Dark, close the app fully and open it again: the first screen the app draws is dark. The native splash screen can still show in the phone's own scheme for a moment, because app.json sets userInterfaceStyle to automatic and the splash appears before any JavaScript runs.
Step 6 · Keep each account in its own store
If two people share a phone, or one person has a work and a personal account, their drafts and filters should not mix. Give each account its own MMKV instance, with an ID built from the user ID, and keep app-wide settings in the settings store. Create each instance once and reuse it.
cd ~/mmkv-settings-demo
cat > src/storage/user-storage.ts <<'TS'
import { createMMKV, deleteMMKV, type MMKV } from 'react-native-mmkv'
// One instance per signed-in account, so two people sharing a phone never see each
// other's drafts or filters. Instances are cached: create each one only once.
const open = new Map<string, MMKV>()
function idFor(userId: string): string {
if (!/^[A-Za-z0-9_-]{1,64}$/.test(userId)) {
throw new Error('A user ID for storage may only use letters, digits, _ and -')
}
return `user-${userId}`
}
export function userStorage(userId: string): MMKV {
const id = idFor(userId)
let storage = open.get(id)
if (!storage) {
storage = createMMKV({ id })
open.set(id, storage)
}
return storage
}
// Call on sign-out: empties the account's values, then removes its file.
export function forgetUser(userId: string): void {
const id = idFor(userId)
userStorage(userId).clearAll()
open.delete(id)
deleteMMKV(id)
}
TS
cat > src/storage/user-storage.test.ts <<'TS'
import { getTheme, setTheme, settings } from './settings'
import { forgetUser, userStorage } from './user-storage'
test('keeps each account separate from the others and from app settings', () => {
userStorage('amina').set('draft.message', 'See you at 10')
userStorage('kofi').set('draft.message', 'Running late')
expect(userStorage('amina').getString('draft.message')).toBe('See you at 10')
expect(userStorage('kofi').getString('draft.message')).toBe('Running late')
expect(settings.contains('draft.message')).toBe(false)
})
test('forgetUser removes one account and leaves the rest', () => {
setTheme('dark')
userStorage('amina').set('draft.message', 'See you at 10')
userStorage('kofi').set('draft.message', 'Running late')
forgetUser('amina')
expect(userStorage('amina').getString('draft.message')).toBeUndefined()
expect(userStorage('kofi').getString('draft.message')).toBe('Running late')
expect(getTheme()).toBe('dark')
})
test('refuses an ID that could escape into a file path', () => {
expect(() => userStorage('../settings')).toThrow()
})
TS
npx jest src/storage/user-storage --ciThe ID becomes part of a file name on the phone, so idFor accepts only letters, digits, _ and -. If your user IDs are email addresses, use the account's numeric or UUID ID instead. Never use an email or phone number, which would also leave personal data in a file name.
Check it worked
Jest reports Tests: 3 passed, 3 total. The second test shows that signing one person out leaves the other account and the app's theme untouched.
Step 7 · Move old values out of AsyncStorage once
An app that already shipped with AsyncStorage has people's settings on their phones. Copy them across on the first launch after the update, mark the move as done in MMKV, and only then delete the old copies. If the app is closed halfway, the next launch copies again, which is harmless because each copy writes the same value.
AsyncStorage stores only strings, so each old key gets its own conversion back to a typed value. Keys not in the list, such as caches, stay where they are. Install the version of AsyncStorage that SDK 58 expects (your app has it already if it used AsyncStorage):
cd ~/mmkv-settings-demo
npx expo install @react-native-async-storage/async-storage
cat > src/storage/migrate-from-async-storage.ts <<'TS'
import {
isThemeChoice,
markOnboardingSeen,
setTextScale,
setTheme,
settings,
TEXT_SCALE_MAX,
TEXT_SCALE_MIN,
} from './settings'
// The three AsyncStorage methods the migration needs. AsyncStorage 2.x has all of them.
export interface LegacyStore {
getAllKeys(): Promise<readonly string[]>
multiGet(keys: readonly string[]): Promise<readonly (readonly [string, string | null])[]>
multiRemove(keys: readonly string[]): Promise<void>
}
const DONE = 'migration.asyncStorage.done'
// Old key -> how to turn its string into a typed MMKV value. Replace these keys
// with the ones your app wrote to AsyncStorage. Anything not listed is left alone.
const LEGACY_KEYS: Record<string, (raw: string) => void> = {
'@prefs/theme': (raw) => {
if (isThemeChoice(raw)) setTheme(raw)
},
'@prefs/onboardingSeen': (raw) => {
if (raw === 'true') markOnboardingSeen()
},
'@prefs/textScale': (raw) => {
const value = Number(raw)
if (value >= TEXT_SCALE_MIN && value <= TEXT_SCALE_MAX) setTextScale(value)
},
}
export function hasMigratedFromAsyncStorage(): boolean {
return settings.getBoolean(DONE) ?? false
}
// Copies known keys once, marks the migration done, then deletes the old copies.
// If the app is closed halfway, the next launch copies again, which is harmless.
export async function migrateFromAsyncStorage(legacy: LegacyStore): Promise<number> {
if (hasMigratedFromAsyncStorage()) return 0
const known = (await legacy.getAllKeys()).filter((key) => key in LEGACY_KEYS)
const pairs = await legacy.multiGet(known)
let copied = 0
for (const [key, raw] of pairs) {
if (raw === null) continue
LEGACY_KEYS[key](raw)
copied++
}
settings.set(DONE, true)
await legacy.multiRemove(known)
return copied
}
TSThe function takes the old store as an argument instead of importing AsyncStorage itself, so the test can pass in AsyncStorage's own in-memory mock:
cd ~/mmkv-settings-demo
cat > src/storage/migrate-from-async-storage.test.ts <<'TS'
import AsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock'
import { getTextScale, getTheme, hasSeenOnboarding, settings } from './settings'
import { hasMigratedFromAsyncStorage, migrateFromAsyncStorage } from './migrate-from-async-storage'
beforeEach(async () => {
settings.clearAll()
await AsyncStorage.clear()
await AsyncStorage.multiSet([
['@prefs/theme', 'dark'],
['@prefs/onboardingSeen', 'true'],
['@prefs/textScale', '1.2'],
['@cache/feed', '[{"id":1}]'],
])
})
test('copies the known keys as typed values and removes them from AsyncStorage', async () => {
const copied = await migrateFromAsyncStorage(AsyncStorage)
expect(copied).toBe(3)
expect(getTheme()).toBe('dark')
expect(hasSeenOnboarding()).toBe(true)
expect(getTextScale()).toBe(1.2)
expect(hasMigratedFromAsyncStorage()).toBe(true)
expect(await AsyncStorage.getAllKeys()).toEqual(['@cache/feed'])
})
test('runs only once', async () => {
await migrateFromAsyncStorage(AsyncStorage)
await AsyncStorage.setItem('@prefs/theme', 'light')
expect(await migrateFromAsyncStorage(AsyncStorage)).toBe(0)
expect(getTheme()).toBe('dark')
})
TS
npx jest src/storage/migrate --ciStart the migration from the root layout. The settings screens work during the move, because they fall back to defaults and update through the hook as soon as each value lands. This version of the layout adds the AsyncStorage import and a second effect to the one from the theme step:
cd ~/mmkv-settings-demo
cat > src/app/_layout.tsx <<'TSX'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { DarkTheme, DefaultTheme, ThemeProvider } from 'expo-router'
import * as SplashScreen from 'expo-splash-screen'
import { useEffect } from 'react'
import { useColorScheme } from 'react-native'
import { AnimatedSplashOverlay } from '@/components/animated-icon'
import AppTabs from '@/components/app-tabs'
import { applyTheme } from '@/storage/apply-theme'
import { migrateFromAsyncStorage } from '@/storage/migrate-from-async-storage'
import { getTheme } from '@/storage/settings'
import { useThemeChoice } from '@/storage/use-theme-choice'
SplashScreen.preventAutoHideAsync()
// MMKV reads synchronously, so the saved theme is applied before anything renders.
applyTheme(getTheme())
export default function RootLayout() {
const [choice] = useThemeChoice()
const scheme = useColorScheme()
useEffect(() => {
applyTheme(choice)
}, [choice])
useEffect(() => {
migrateFromAsyncStorage(AsyncStorage).catch((error) => {
console.warn('Settings migration failed; it will run again next launch', error)
})
}, [])
return (
<ThemeProvider value={scheme === 'dark' ? DarkTheme : DefaultTheme}>
<AnimatedSplashOverlay />
<AppTabs />
</ThemeProvider>
)
}
TSXLeave the migration in place for a few releases, until almost nobody is updating from a version that used AsyncStorage, then remove it and the AsyncStorage package.
Check it worked
Jest reports Tests: 2 passed, 2 total. The first test shows 'true' coming back as the boolean true and '1.2' as the number 1.2, and the unrelated cache key is still in AsyncStorage.
Step 8 · Treat the encryption key as a lock, not a safe
createMMKV accepts an encryptionKey, and MMKV then encrypts its file with AES (a key of up to 16 bytes for AES-128, or 32 bytes for AES-256). It is tempting to type a key into the code and call the store secure. It is not: anything you write in JavaScript ships inside the app bundle, and anyone who downloads your app can read it. Export the Android bundle and look for a piece of text from the theme picker:
cd ~/mmkv-settings-demo
npx expo export --platform android
grep -a -o "Match the phone" dist/_expo/static/js/android/*.hbc | head -n 1The label prints, straight out of the compiled bundle. A hard-coded encryption key would sit in the same file, next to the code that uses it.
So:
- keep secrets out of MMKV altogether. Tokens and passwords go into the Keychain or Keystore through
expo-secure-store, which the operating system protects with the device lock. - if you must encrypt an MMKV store, for example a cache of messages, generate a random key on the phone on first launch, keep that key in
expo-secure-store, and pass it tocreateMMKVwhen the app starts. The key then never appears in the bundle, and it is different on every phone. - remember that a settings store does not need encryption. A theme or a text size tells an attacker nothing.
Check it worked
cd ~/mmkv-settings-demo
grep -a -c "MMKVFactory" dist/_expo/static/js/android/*.hbc
grep -rn "encryptionKey" src || echo "no encryption keys in the source"
npx jest --ciThe first command prints 1 or more, which shows MMKV is in the Android bundle. The second prints no encryption keys in the source, and the full Jest run reports four test suites with Tests: 11 passed, 11 total.
Next steps
- Store records that need sorting and filtering in SQLite with expo-sqlite.
- Keep sign-in tokens in the Keychain and Keystore with expo-secure-store.
- If you are new to Expo, start with creating your first Expo app.
- To delete the demo, remove the folder:
rm -rf ~/mmkv-settings-demo.
Related tutorials
- How to Create Your First React Native App with ExpoYou will create an Expo SDK 58 project with TypeScript, look at what the template gives you, run it on your phone or in a simulator, replace the home screen with a small counter of your own, and check from the command line that the project bundles and passes expo-doctor.
- Store Larkfield appointments on the phone with expo-sqliteYou will have the Larkfield app saving bookings to an SQLite database on the phone, with versioned migrations, bound parameters, all-or-nothing writes and an Appointments tab that updates itself, all covered by Jest tests.
- Keep sign-in tokens safe on the phone with expo-secure-storeYou will have an Expo SDK 58 app that keeps its refresh token in the iOS Keychain or Android Keystore, holds the access token in memory only, asks for Face ID or a fingerprint before a transfer, starts clean after a reinstall and signs out by deleting every key, with Jest tests for all of it.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials