Repository: mrousavy/react-native-mmkv
Branch: main
Commit: 3df2075e9f36
Files: 168
Total size: 319.3 KB
Directory structure:
gitextract_dgxiax_y/
├── .clang-format
├── .github/
│ ├── FUNDING.yml
│ ├── dependabot.yml
│ └── workflows/
│ ├── build-android-release.yml
│ ├── build-android.yml
│ ├── build-ios-release.yml
│ ├── build-ios.yml
│ ├── harness-android.yml
│ ├── harness-ios.yml
│ ├── lint-cpp.yml
│ ├── lint-typescript.yml
│ ├── run-nitrogen.yml
│ ├── test-js.yml
│ └── update-lockfiles.yml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── README_V3.md
├── babel.config.js
├── bunfig.toml
├── docs/
│ ├── HOOKS.md
│ ├── LISTENERS.md
│ ├── MIGRATE_FROM_ASYNC_STORAGE.md
│ ├── V4_UPGRADE_GUIDE.md
│ ├── WRAPPER_JOTAI.md
│ ├── WRAPPER_MOBX.md
│ ├── WRAPPER_MOBXPERSIST.md
│ ├── WRAPPER_REACT_QUERY.md
│ ├── WRAPPER_RECOIL.md
│ ├── WRAPPER_REDUX.md
│ ├── WRAPPER_TINYBASE.md
│ └── WRAPPER_ZUSTAND_PERSIST_MIDDLEWARE.md
├── example/
│ ├── .eslintrc.js
│ ├── .gitignore
│ ├── .prettierrc.js
│ ├── .watchmanconfig
│ ├── Gemfile
│ ├── README.md
│ ├── __tests__/
│ │ └── MMKV.harness.ts
│ ├── android/
│ │ ├── app/
│ │ │ ├── build.gradle
│ │ │ ├── debug.keystore
│ │ │ ├── proguard-rules.pro
│ │ │ └── src/
│ │ │ └── main/
│ │ │ ├── AndroidManifest.xml
│ │ │ ├── java/
│ │ │ │ └── com/
│ │ │ │ └── mrousavy/
│ │ │ │ └── mmkv/
│ │ │ │ └── example/
│ │ │ │ ├── MainActivity.kt
│ │ │ │ └── MainApplication.kt
│ │ │ └── res/
│ │ │ ├── drawable/
│ │ │ │ └── rn_edit_text_material.xml
│ │ │ └── values/
│ │ │ ├── strings.xml
│ │ │ └── styles.xml
│ │ ├── build.gradle
│ │ ├── gradle/
│ │ │ └── wrapper/
│ │ │ ├── gradle-wrapper.jar
│ │ │ └── gradle-wrapper.properties
│ │ ├── gradle.properties
│ │ ├── gradlew
│ │ ├── gradlew.bat
│ │ └── settings.gradle
│ ├── app.json
│ ├── babel.config.js
│ ├── index.js
│ ├── ios/
│ │ ├── .xcode.env
│ │ ├── MmkvExample/
│ │ │ ├── AppDelegate.swift
│ │ │ ├── Images.xcassets/
│ │ │ │ ├── AppIcon.appiconset/
│ │ │ │ │ └── Contents.json
│ │ │ │ └── Contents.json
│ │ │ ├── Info.plist
│ │ │ ├── LaunchScreen.storyboard
│ │ │ └── PrivacyInfo.xcprivacy
│ │ ├── MmkvExample.xcodeproj/
│ │ │ ├── project.pbxproj
│ │ │ └── xcshareddata/
│ │ │ └── xcschemes/
│ │ │ └── MmkvExample.xcscheme
│ │ ├── MmkvExample.xcworkspace/
│ │ │ └── contents.xcworkspacedata
│ │ └── Podfile
│ ├── jest.config.js
│ ├── metro.config.js
│ ├── package.json
│ ├── rn-harness.config.mjs
│ ├── src/
│ │ └── App.tsx
│ └── tsconfig.json
├── jest.config.js
├── package.json
├── packages/
│ └── react-native-mmkv/
│ ├── .gitignore
│ ├── .watchmanconfig
│ ├── NitroMmkv.podspec
│ ├── README.md
│ ├── __bun_tests__/
│ │ └── use-jest-instead.test.ts
│ ├── __mocks__/
│ │ └── react-native-nitro-modules.js
│ ├── android/
│ │ ├── CMakeLists.txt
│ │ ├── build.gradle
│ │ ├── fix-prefab.gradle
│ │ ├── gradle.properties
│ │ └── src/
│ │ └── main/
│ │ ├── AndroidManifest.xml
│ │ ├── cpp/
│ │ │ └── cpp-adapter.cpp
│ │ └── java/
│ │ └── com/
│ │ └── margelo/
│ │ └── nitro/
│ │ └── mmkv/
│ │ ├── HybridMMKVPlatformContext.kt
│ │ └── NitroMmkvPackage.java
│ ├── babel.config.js
│ ├── cpp/
│ │ ├── HybridMMKV.cpp
│ │ ├── HybridMMKV.hpp
│ │ ├── HybridMMKVFactory.cpp
│ │ ├── HybridMMKVFactory.hpp
│ │ ├── MMKVTypes.hpp
│ │ ├── MMKVValueChangedListenerRegistry.cpp
│ │ ├── MMKVValueChangedListenerRegistry.hpp
│ │ └── ManagedMMBuffer.hpp
│ ├── ios/
│ │ └── HybridMMKVPlatformContext.swift
│ ├── nitro.json
│ ├── nitrogen/
│ │ └── generated/
│ │ ├── .gitattributes
│ │ ├── android/
│ │ │ ├── NitroMmkv+autolinking.cmake
│ │ │ ├── NitroMmkv+autolinking.gradle
│ │ │ ├── NitroMmkvOnLoad.cpp
│ │ │ ├── NitroMmkvOnLoad.hpp
│ │ │ ├── c++/
│ │ │ │ ├── JHybridMMKVPlatformContextSpec.cpp
│ │ │ │ └── JHybridMMKVPlatformContextSpec.hpp
│ │ │ └── kotlin/
│ │ │ └── com/
│ │ │ └── margelo/
│ │ │ └── nitro/
│ │ │ └── mmkv/
│ │ │ ├── HybridMMKVPlatformContextSpec.kt
│ │ │ └── NitroMmkvOnLoad.kt
│ │ ├── ios/
│ │ │ ├── NitroMmkv+autolinking.rb
│ │ │ ├── NitroMmkv-Swift-Cxx-Bridge.cpp
│ │ │ ├── NitroMmkv-Swift-Cxx-Bridge.hpp
│ │ │ ├── NitroMmkv-Swift-Cxx-Umbrella.hpp
│ │ │ ├── NitroMmkvAutolinking.mm
│ │ │ ├── NitroMmkvAutolinking.swift
│ │ │ ├── c++/
│ │ │ │ ├── HybridMMKVPlatformContextSpecSwift.cpp
│ │ │ │ └── HybridMMKVPlatformContextSpecSwift.hpp
│ │ │ └── swift/
│ │ │ ├── HybridMMKVPlatformContextSpec.swift
│ │ │ └── HybridMMKVPlatformContextSpec_cxx.swift
│ │ └── shared/
│ │ └── c++/
│ │ ├── Configuration.hpp
│ │ ├── EncryptionType.hpp
│ │ ├── HybridMMKVFactorySpec.cpp
│ │ ├── HybridMMKVFactorySpec.hpp
│ │ ├── HybridMMKVPlatformContextSpec.cpp
│ │ ├── HybridMMKVPlatformContextSpec.hpp
│ │ ├── HybridMMKVSpec.cpp
│ │ ├── HybridMMKVSpec.hpp
│ │ ├── Listener.hpp
│ │ └── Mode.hpp
│ ├── package.json
│ ├── react-native.config.js
│ ├── src/
│ │ ├── __tests__/
│ │ │ └── hooks.test.tsx
│ │ ├── addMemoryWarningListener/
│ │ │ ├── addMemoryWarningListener.mock.ts
│ │ │ ├── addMemoryWarningListener.ts
│ │ │ └── addMemoryWarningListener.web.ts
│ │ ├── createMMKV/
│ │ │ ├── createMMKV.ts
│ │ │ ├── createMMKV.web.ts
│ │ │ ├── createMockMMKV.ts
│ │ │ └── getDefaultMMKVInstance.ts
│ │ ├── deleteMMKV/
│ │ │ ├── deleteMMKV.ts
│ │ │ └── deleteMMKV.web.ts
│ │ ├── existsMMKV/
│ │ │ ├── existsMMKV.ts
│ │ │ └── existsMMKV.web.ts
│ │ ├── getMMKVFactory.ts
│ │ ├── hooks/
│ │ │ ├── createMMKVHook.ts
│ │ │ ├── useMMKV.ts
│ │ │ ├── useMMKVBoolean.ts
│ │ │ ├── useMMKVBuffer.ts
│ │ │ ├── useMMKVKeys.ts
│ │ │ ├── useMMKVListener.ts
│ │ │ ├── useMMKVNumber.ts
│ │ │ ├── useMMKVObject.ts
│ │ │ └── useMMKVString.ts
│ │ ├── index.ts
│ │ ├── isTest.ts
│ │ ├── specs/
│ │ │ ├── MMKV.nitro.ts
│ │ │ ├── MMKVFactory.nitro.ts
│ │ │ └── MMKVPlatformContext.nitro.ts
│ │ └── web/
│ │ ├── createTextDecoder.ts
│ │ ├── createTextEncoder.ts
│ │ └── getLocalStorage.ts
│ └── tsconfig.json
└── scripts/
├── clang-format.sh
└── release.sh
================================================
FILE CONTENTS
================================================
================================================
FILE: .clang-format
================================================
# Config for clang-format version 16
# Standard
BasedOnStyle: llvm
Standard: c++20
# Indentation
IndentWidth: 2
ColumnLimit: 140
# Includes
SortIncludes: CaseSensitive
SortUsingDeclarations: true
# Pointer and reference alignment
PointerAlignment: Left
ReferenceAlignment: Left
ReflowComments: true
# Line breaking options
BreakBeforeBraces: Attach
BreakConstructorInitializers: BeforeColon
AlwaysBreakTemplateDeclarations: true
AllowShortFunctionsOnASingleLine: Empty
IndentCaseLabels: true
NamespaceIndentation: Inner
================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms
github: mrousavy
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: mrousavy
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
================================================
FILE: .github/dependabot.yml
================================================
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
labels:
- "dependencies"
- package-ecosystem: "gradle"
directory: "/packages/react-native-mmkv/android/"
schedule:
interval: "weekly"
labels:
- "dependencies"
================================================
FILE: .github/workflows/build-android-release.yml
================================================
name: Build Android (Release)
on:
release:
types: [published]
pull_request:
paths:
- '.github/workflows/build-android-release.yml'
jobs:
build_release:
name: Build Android Example App (release, new architecture)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@v2
- name: Install npm dependencies (bun)
run: bun install
- name: Install npm dependencies in example/ (bun)
working-directory: example
run: bun install
- name: Setup JDK 17
uses: actions/setup-java@v5
with:
distribution: 'zulu'
java-version: 17
java-package: jdk
- name: Run Gradle Build for example/android/
working-directory: example
run: bun run build:android-release
- name: Upload APK to Release
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ github.event.release.upload_url }}
asset_path: example/android/app/build/outputs/apk/release/app-release.apk
asset_name: "MmkvExample-${{ github.event.release.tag_name }}.apk"
asset_content_type: application/vnd.android.package-archive
# Gradle cache doesn't like daemons
- name: Stop Gradle Daemon
working-directory: example/android
run: ./gradlew --stop
================================================
FILE: .github/workflows/build-android.yml
================================================
name: Build Android
on:
push:
branches:
- main
paths:
- '.github/workflows/build-android.yml'
- 'example/android/**'
- '**/nitrogen/generated/shared/**'
- '**/nitrogen/generated/android/**'
- 'packages/react-native-mmkv/cpp/**'
- 'packages/react-native-mmkv/android/**'
- '**/bun.lock'
- '**/react-native.config.js'
- '**/nitro.json'
pull_request:
paths:
- '.github/workflows/build-android.yml'
- 'example/android/**'
- '**/nitrogen/generated/shared/**'
- '**/nitrogen/generated/android/**'
- 'packages/react-native-mmkv/cpp/**'
- 'packages/react-native-mmkv/android/**'
- '**/bun.lock'
- '**/react-native.config.js'
- '**/nitro.json'
jobs:
build:
name: Build Android Example App
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@v2
- name: Install npm dependencies (bun)
run: bun install
- name: Setup JDK 17
uses: actions/setup-java@v5
with:
distribution: 'zulu'
java-version: 17
java-package: jdk
- name: Restore Gradle cache
uses: actions/cache@v5
with:
path: |
~/.gradle/caches
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
${{ runner.os }}-gradle-
- name: Run Gradle Build for example/android/
working-directory: example/android
run: ./gradlew assembleDebug --no-daemon --build-cache
# Gradle cache doesn't like daemons
- name: Stop Gradle Daemon
working-directory: example/android
run: ./gradlew --stop
================================================
FILE: .github/workflows/build-ios-release.yml
================================================
name: Build iOS (Release)
on:
release:
types: [published]
pull_request:
paths:
- '.github/workflows/build-ios-release.yml'
jobs:
build_release:
name: Build iOS Example App (release, new architecture)
runs-on: macos-latest
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@v2
- name: Install npm dependencies (bun)
run: bun install
- name: Install npm dependencies in example/ (bun)
working-directory: example
run: bun install
- name: Setup Ruby (bundle)
uses: ruby/setup-ruby@v1
with:
ruby-version: 2.7.2
bundler-cache: true
working-directory: example
- name: Select Xcode 16.4
run: sudo xcode-select -s "/Applications/Xcode_16.4.app/Contents/Developer"
- name: Restore Pods cache
uses: actions/cache@v5
with:
path: example/ios/Pods
key: ${{ runner.os }}-pods-${{ hashFiles('**/Podfile.lock', '**/Gemfile.lock') }}
restore-keys: |
${{ runner.os }}-pods-
- name: Install Pods
working-directory: example
run: bun pods
- name: Build App (Release, Simulator)
working-directory: example/ios
run: |
set -o pipefail
xcodebuild \
CC=clang CPLUSPLUS=clang++ LD=clang LDPLUSPLUS=clang++ \
-derivedDataPath build -UseModernBuildSystem=YES \
-workspace MmkvExample.xcworkspace \
-scheme MmkvExample \
-sdk iphonesimulator \
-configuration Release \
-destination 'generic/platform=iOS Simulator' \
build \
CODE_SIGNING_ALLOWED=NO
- name: Package .app for Simulator
run: |
cd example/ios/build/Build/Products/Release-iphonesimulator
zip -r ../../../../../../MmkvExample-Release-Simulator.zip MmkvExample.app
- name: Upload .app to Release
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ github.event.release.upload_url }}
asset_path: MmkvExample-Release-Simulator.zip
asset_name: "MmkvExample-Simulator-${{ github.event.release.tag_name }}.app.zip"
asset_content_type: application/zip
================================================
FILE: .github/workflows/build-ios.yml
================================================
name: Build iOS
on:
push:
branches:
- main
paths:
- '.github/workflows/build-ios.yml'
- 'example/ios/**'
- '**/nitrogen/generated/shared/**'
- '**/nitrogen/generated/ios/**'
- 'packages/react-native-mmkv/cpp/**'
- 'packages/react-native-mmkv/ios/**'
- '**/Podfile.lock'
- '**/*.podspec'
- '**/react-native.config.js'
- '**/nitro.json'
pull_request:
paths:
- '.github/workflows/build-ios.yml'
- 'example/ios/**'
- '**/nitrogen/generated/shared/**'
- '**/nitrogen/generated/ios/**'
- 'packages/react-native-mmkv/cpp/**'
- 'packages/react-native-mmkv/ios/**'
- '**/Podfile.lock'
- '**/*.podspec'
- '**/react-native.config.js'
- '**/nitro.json'
env:
USE_CCACHE: 1
# Must match the runner's architecture (macOS-15 runners are arm64)
ARCH: arm64
jobs:
build:
name: Build iOS Example App
runs-on: macOS-15
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@v2
- name: Install npm dependencies (bun)
run: bun install
- name: Restore ccache
uses: hendrikmuhs/ccache-action@v1.2
- name: Setup Ruby (bundle)
uses: ruby/setup-ruby@v1
with:
ruby-version: 2.7.2
bundler-cache: true
working-directory: example
- name: Select Xcode 16.4
run: sudo xcode-select -s "/Applications/Xcode_16.4.app/Contents/Developer"
- name: Restore Pods cache
uses: actions/cache@v5
with:
path: example/ios/Pods
key: ${{ runner.os }}-pods-${{ hashFiles('**/Podfile.lock', '**/Gemfile.lock') }}
restore-keys: |
${{ runner.os }}-pods-
- name: Install Pods
working-directory: example
run: bun pods
- name: Build App
working-directory: example/ios
run: "set -o pipefail && xcodebuild \
CC=clang CPLUSPLUS=clang++ LD=clang LDPLUSPLUS=clang++ \
-derivedDataPath build -UseModernBuildSystem=YES \
-workspace MmkvExample.xcworkspace \
-scheme MmkvExample \
-sdk iphonesimulator \
-configuration Debug \
-destination 'generic/platform=iOS Simulator,arch=${{ env.ARCH }}' \
build \
CODE_SIGNING_ALLOWED=NO"
================================================
FILE: .github/workflows/harness-android.yml
================================================
name: Harness Android
on:
workflow_dispatch:
inputs:
device_api_level:
description: "Android API level for the emulator"
required: false
default: "35"
type: string
device_arch:
description: "Device architecture (x86_64, arm64-v8a)"
required: false
default: "x86_64"
type: choice
options:
- x86_64
- arm64-v8a
device_profile:
description: "Device profile"
required: false
default: "pixel_7"
type: string
avd_name:
description: "AVD name"
required: false
default: "Pixel_8_API_35"
type: string
push:
branches:
- main
paths:
- ".github/workflows/harness-android.yml"
- "example/android/**"
- "**/nitrogen/generated/shared/**"
- "**/nitrogen/generated/android/**"
- "packages/react-native-mmkv/cpp/**"
- "packages/react-native-mmkv/android/**"
- "**/bun.lock"
- "**/react-native.config.js"
- "**/nitro.json"
- "example/__tests__/**"
- "example/rn-harness.config.mjs"
pull_request:
paths:
- ".github/workflows/harness-android.yml"
- "example/android/**"
- "**/nitrogen/generated/shared/**"
- "**/nitrogen/generated/android/**"
- "packages/react-native-mmkv/cpp/**"
- "packages/react-native-mmkv/android/**"
- "**/bun.lock"
- "**/react-native.config.js"
- "**/nitro.json"
- "example/__tests__/**"
- "example/rn-harness.config.mjs"
env:
# Device configuration - can be overridden by workflow_dispatch inputs
DEVICE_API_LEVEL: ${{ github.event.inputs.device_api_level || '35' }}
DEVICE_ARCH: ${{ github.event.inputs.device_arch || 'x86_64' }}
DEVICE_PROFILE: ${{ github.event.inputs.device_profile || 'pixel_7' }}
AVD_NAME: ${{ github.event.inputs.avd_name || 'Pixel_8_API_35' }}
jobs:
harness_android_new:
name: Harness Android (new architecture)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@v2
- name: Install npm dependencies (bun)
run: bun install
- name: Setup JDK 17
uses: actions/setup-java@v5
with:
distribution: "zulu"
java-version: 17
java-package: jdk
- name: Restore Gradle cache
uses: actions/cache@v5
with:
path: |
~/.gradle/caches
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
${{ runner.os }}-gradle-
- name: Build Android app
working-directory: example/android
run: ./gradlew assembleDebug --no-daemon --build-cache
- name: Enable KVM group perms
run: |
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
sudo udevadm control --reload-rules
sudo udevadm trigger --name-match=kvm
ls /dev/kvm
- name: AVD cache
uses: actions/cache@v5
id: avd-cache
with:
path: |
~/.android/avd/*
~/.android/adb*
key: avd-${{ env.DEVICE_API_LEVEL }}-${{ env.DEVICE_ARCH }}
- name: Create AVD and generate snapshot for caching
if: steps.avd-cache.outputs.cache-hit != 'true'
uses: reactivecircus/android-emulator-runner@v2
with:
api-level: ${{ env.DEVICE_API_LEVEL }}
arch: ${{ env.DEVICE_ARCH }}
profile: ${{ env.DEVICE_PROFILE }}
disk-size: 1G
heap-size: 1G
force-avd-creation: false
avd-name: ${{ env.AVD_NAME }}
disable-animations: true
emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none
script: echo "Generated AVD snapshot for caching."
- name: Run Harness E2E tests
uses: reactivecircus/android-emulator-runner@v2
with:
working-directory: example
api-level: ${{ env.DEVICE_API_LEVEL }}
arch: ${{ env.DEVICE_ARCH }}
force-avd-creation: false
avd-name: ${{ env.AVD_NAME }}
disable-animations: true
emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none
script: |
adb install -r "./android/app/build/outputs/apk/debug/app-debug.apk"
bun run test:harness --harnessRunner android
# Gradle cache doesn't like daemons
- name: Stop Gradle Daemon
working-directory: example/android
run: ./gradlew --stop
================================================
FILE: .github/workflows/harness-ios.yml
================================================
name: Harness iOS
on:
workflow_dispatch:
inputs:
device_model:
description: "iOS Simulator device model"
required: false
default: "iPhone 16 Pro"
type: string
ios_version:
description: "iOS version"
required: false
default: "18.6"
type: string
xcode_version:
description: "Xcode version"
required: false
default: "16.4.0"
type: string
push:
branches:
- main
paths:
- ".github/workflows/harness-ios.yml"
- "example/ios/**"
- "**/nitrogen/generated/shared/**"
- "**/nitrogen/generated/ios/**"
- "packages/react-native-mmkv/cpp/**"
- "packages/react-native-mmkv/ios/**"
- "**/Podfile.lock"
- "**/*.podspec"
- "**/react-native.config.js"
- "**/nitro.json"
- "example/__tests__/**"
- "example/rn-harness.config.mjs"
pull_request:
paths:
- ".github/workflows/harness-ios.yml"
- "example/ios/**"
- "**/nitrogen/generated/shared/**"
- "**/nitrogen/generated/ios/**"
- "packages/react-native-mmkv/cpp/**"
- "packages/react-native-mmkv/ios/**"
- "**/Podfile.lock"
- "**/*.podspec"
- "**/react-native.config.js"
- "**/nitro.json"
- "example/__tests__/**"
- "example/rn-harness.config.mjs"
env:
# Device configuration - can be overridden by workflow_dispatch inputs
DEVICE_MODEL: ${{ github.event.inputs.device_model || 'iPhone 16 Pro' }}
IOS_VERSION: ${{ github.event.inputs.ios_version || '18.6' }}
XCODE_VERSION: ${{ github.event.inputs.xcode_version || '16.4.0' }}
USE_CCACHE: 1
DEVELOPER_DIR: /Applications/Xcode_${{ github.event.inputs.xcode_version || '16.4.0' }}.app/Contents/Developer
jobs:
harness_ios_new:
name: Harness iOS (new architecture)
runs-on: macos-latest
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@v2
- name: Install npm dependencies (bun)
run: bun install
- name: Restore ccache
uses: hendrikmuhs/ccache-action@v1.2
- name: Setup Ruby (bundle)
uses: ruby/setup-ruby@v1
with:
ruby-version: 2.7.2
bundler-cache: true
working-directory: example
- name: Select Xcode ${{ env.XCODE_VERSION }}
run: sudo xcode-select -s "/Applications/Xcode_${{ env.XCODE_VERSION }}.app/Contents/Developer"
- name: Restore Pods cache
uses: actions/cache@v5
with:
path: example/ios/Pods
key: ${{ runner.os }}-pods-${{ hashFiles('**/Podfile.lock', '**/Gemfile.lock') }}
restore-keys: |
${{ runner.os }}-pods-
- name: Install Pods
working-directory: example
run: bun pods
- name: Build iOS app
working-directory: example/ios
run: "set -o pipefail && xcodebuild \
CC=clang CPLUSPLUS=clang++ LD=clang LDPLUSPLUS=clang++ \
-derivedDataPath build -UseModernBuildSystem=YES \
-workspace MmkvExample.xcworkspace \
-scheme MmkvExample \
-sdk iphonesimulator \
-configuration Debug \
-destination 'platform=iOS Simulator,name=${{ env.DEVICE_MODEL }}' \
build \
CODE_SIGNING_ALLOWED=NO"
- name: Setup iOS Simulator
uses: futureware-tech/simulator-action@v5
with:
model: ${{ env.DEVICE_MODEL }}
os: iOS
os_version: ${{ env.IOS_VERSION }}
wait_for_boot: true
erase_before_boot: false
- name: Install app
run: |
xcrun simctl install booted example/ios/build/Build/Products/Debug-iphonesimulator/MmkvExample.app
- name: Run Harness E2E tests
working-directory: example
run: |
bun run test:harness --harnessRunner ios
================================================
FILE: .github/workflows/lint-cpp.yml
================================================
name: Validate C++
on:
push:
branches:
- main
paths:
- '.github/workflows/lint-cpp.yml'
- '**/*.h'
- '**/*.hpp'
- '**/*.cpp'
- '**/*.c'
- '**/*.mm'
pull_request:
paths:
- '.github/workflows/lint-cpp.yml'
- '**/*.h'
- '**/*.hpp'
- '**/*.cpp'
- '**/*.c'
- '**/*.mm'
jobs:
lint:
name: Check clang-format
runs-on: ubuntu-latest
strategy:
matrix:
path:
- 'packages/react-native-mmkv/android/src/main/cpp'
- 'packages/react-native-mmkv/cpp'
- 'packages/react-native-mmkv/ios'
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@v2
- name: Install npm dependencies (bun)
run: bun install
- name: Run clang-format style check
uses: jidicula/clang-format-action@v4.17.0
with:
clang-format-version: '18'
check-path: ${{ matrix.path }}
================================================
FILE: .github/workflows/lint-typescript.yml
================================================
name: Lint TypeScript
permissions:
checks: write
contents: read
pull-requests: read
on:
push:
branches:
- main
paths:
- '.github/workflows/lint-typescript.yml'
- 'config'
- '**/*.ts'
- '**/*.tsx'
- '**/*.js'
- '**/*.jsx'
- '**/*.json'
- '**/*.lockb'
- '**/package.json'
pull_request:
paths:
- '.github/workflows/lint-typescript.yml'
- 'config'
- '**/*.ts'
- '**/*.tsx'
- '**/*.js'
- '**/*.jsx'
- '**/*.json'
- '**/*.lockb'
- '**/package.json'
jobs:
tsc:
name: Compile TypeScript (tsc)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@v2
- uses: reviewdog/action-setup@v1
- name: Install npm dependencies (bun)
run: bun install
- name: Run TypeScript (tsc)
run: |
bun typecheck | reviewdog -name="tsc" -efm="%f(%l,%c): error TS%n: %m" -reporter="github-pr-review" -filter-mode="nofilter" -fail-on-error -tee
env:
REVIEWDOG_GITHUB_API_TOKEN: ${{ secrets.GITHUB_TOKEN }}
lint:
name: Lint JS (eslint, prettier)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@v2
- uses: reviewdog/action-setup@v1
- name: Install npm dependencies (bun)
run: bun install
- name: Run ESLint CI in example/
working-directory: example
run: bun lint-ci
- name: Run ESLint CI in packages/react-native-mmkv
working-directory: packages/react-native-mmkv
run: bun lint-ci
- name: Run ESLint with auto-fix in example/
working-directory: example
run: bun lint
- name: Run ESLint with auto-fix in packages/react-native-mmkv
working-directory: packages/react-native-mmkv
run: bun lint
- name: Verify no files have changed after auto-fix
run: git diff --exit-code HEAD -- . ':(exclude)bun.lock'
================================================
FILE: .github/workflows/run-nitrogen.yml
================================================
name: Run Nitrogen
on:
push:
branches:
- main
paths:
- '.github/workflows/run-nitrogen.yml'
- '**/*.ts'
- '**/*.tsx'
- '**/*.js'
- '**/*.jsx'
- '**/*.json'
- '**/*.lockb'
- '**/nitro.json'
- '**/package.json'
pull_request:
paths:
- '.github/workflows/run-nitrogen.yml'
- '**/*.ts'
- '**/*.tsx'
- '**/*.js'
- '**/*.jsx'
- '**/*.json'
- '**/*.lockb'
- '**/nitro.json'
- '**/package.json'
jobs:
lint:
name: Run Nitrogen for react-native-mmkv
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@v2
- name: Install npm dependencies (bun)
run: bun install
- name: Build all packages
run: bun mmkv build
- name: Run nitrogen in packages/react-native-mmkv
working-directory: packages/react-native-mmkv
run: bun i && bun specs
- name: Verify no files have changed after nitrogen
run: git diff --exit-code HEAD -- . ':(exclude)bun.lock'
================================================
FILE: .github/workflows/test-js.yml
================================================
name: Test JS
on:
push:
branches:
- main
paths:
- '.github/workflows/test-js.yml'
- 'packages/react-native-mmkv/**'
pull_request:
paths:
- '.github/workflows/test-js.yml'
- 'packages/react-native-mmkv/**'
jobs:
test:
name: Test JS
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@v2
- name: Install npm dependencies (bun)
run: bun install
- name: Run Jest
run: bun run test
================================================
FILE: .github/workflows/update-lockfiles.yml
================================================
name: 'Update Lockfiles (bun.lock + Podfile.lock)'
on:
push:
branches:
- main
paths:
- ".github/workflows/update-lockfiles.yml"
pull_request:
paths:
- ".github/workflows/update-lockfiles.yml"
- "package.json"
- "**/package.json"
permissions:
contents: write
jobs:
update-lockfiles:
name: "Update lockfiles (Podfile.lock)"
if: github.actor == 'dependabot[bot]'
runs-on: macOS-latest
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
ref: ${{ github.event.pull_request.head.ref }}
- uses: oven-sh/setup-bun@v2
- name: Setup Ruby (bundle)
uses: ruby/setup-ruby@v1
with:
ruby-version: 2.7.2
bundler-cache: true
working-directory: example/ios
- run: |
bun install
cd example
bundle install
bun pods
cd ..
cd docs
bun install
cd ..
git add bun.lock
git add example/ios/Podfile.lock
git add example/Gemfile.lock
git config --global user.name 'dependabot[bot]'
git config --global user.email 'dependabot[bot]@users.noreply.github.com'
git commit --amend --no-edit
git push --force
================================================
FILE: .gitignore
================================================
.DS_Store
**/node_modules/
# no yarn/npm in the root repo!
/package-lock.json
/yarn.lock
.xcode.env.local
.vscode
# build
.cache
build
compile_commands.json
**/tsconfig.tsbuildinfo
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, caste, color, religion, or sexual
identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall
community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of
any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address,
without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
[INSERT CONTACT METHOD].
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of
actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or permanent
ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the
community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.1, available at
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
For answers to common questions about this code of conduct, see the FAQ at
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
[https://www.contributor-covenant.org/translations][translations].
[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing
Contributions are always welcome, no matter how large or small!
We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project. Before contributing, please read the [code of conduct](./CODE_OF_CONDUCT.md).
## Development workflow
To get started with the project, run `bun i` in the root directory to install the required dependencies for all packages & apps:
```sh
bun i
```
The [example app](/example/) demonstrates usage of the library. You need to run it to test any changes you make.
It is configured to use the local version of the library, so any changes you make to the library's source code will be reflected in the example app. Changes to the library's JavaScript code will be reflected in the example app without a rebuild, but native code changes will require a rebuild of the example app.
If you want to use Android Studio or XCode to edit the native code, you can open the `example/android` or `example/ios` directories respectively in those editors. To edit the Objective-C or Swift files, open `example/ios/MmkvExample.xcworkspace` in XCode and find the source files at `Pods > Development Pods > react-native-mmkv`.
To edit the Java or Kotlin files, open `example/android` in Android studio and find the source files at `react-native-mmkv` under `Android`.
You can use various commands from the root directory to work with the project.
To start the packager:
```sh
bun example start
```
To run the example app on Android:
```sh
bun example android
```
To run the example app on iOS:
```sh
bun example ios
```
To confirm that the app is running with the new architecture, you can check the Metro logs for a message like this:
```sh
Running "MmkvExample" with {"fabric":true,"initialProps":{"concurrentRoot":true},"rootTag":1}
```
Note the `"fabric":true` and `"concurrentRoot":true` properties.
Make sure your code passes TypeScript and ESLint. Run the following to verify:
```sh
bun typecheck
bun lint
```
To fix formatting errors, run the following:
```sh
bun lint --fix
```
Remember to add tests for your change if possible. Run the unit tests by:
```sh
# `bun test` uses bun's test runner, which isn't compatible with flow notation
# in RN. So use `bun run test`
bun run test
```
### Commit message convention
We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages:
- `fix`: bug fixes, e.g. fix crash due to deprecated method.
- `feat`: new features, e.g. add new method to the module.
- `refactor`: code refactor, e.g. migrate from class components to hooks.
- `docs`: changes into documentation, e.g. add usage example for the module..
- `test`: adding or updating tests, e.g. add integration tests using detox.
- `chore`: tooling changes, e.g. change CI config.
Our pre-commit hooks verify that your commit message matches this format when committing.
### Linting and tests
[ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/)
We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing.
Our pre-commit hooks verify that the linter and tests pass when committing.
### Publishing to npm
We use [release-it](https://github.com/release-it/release-it) to make it easier to publish new versions. It handles common tasks like bumping version based on semver, creating tags and releases etc.
To publish new versions, run the following:
```sh
bun release
```
### Scripts
The `package.json` file contains various scripts for common tasks:
- `bun`: setup project by installing dependencies.
- `bun typecheck`: type-check files with TypeScript.
- `bun lint`: lint files with ESLint.
- `bun test`: run unit tests with Jest.
- `bun example start`: start the Metro server for the example app.
- `bun example android`: run the example app on Android.
- `bun example ios`: run the example app on iOS.
### Sending a pull request
> **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://app.egghead.io/playlists/how-to-contribute-to-an-open-source-project-on-github).
When you're sending a pull request:
- Prefer small pull requests focused on one change.
- Verify that linters and tests are passing.
- Review the documentation to make sure it looks good.
- Follow the pull request template when opening a pull request.
- For pull requests that change the API or implementation, discuss with maintainers first by opening an issue.
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2024 Marc Rousavy
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
| **V4 Docs** | [old V3 Docs](./README_V3.md) |
|:---|:---|
MMKV
The fastest key/value storage for React Native.
* **MMKV** is an efficient, small mobile key-value storage framework developed by WeChat. See [Tencent/MMKV](https://github.com/Tencent/MMKV) for more information
* **react-native-mmkv** is a library that allows you to easily use **MMKV** inside your React Native app through fast and direct JS bindings to the native C++ library.
## Features
* **Get** and **set** strings, booleans, numbers and ArrayBuffers
* **Fully synchronous** calls, no async/await, no Promises, no Bridge.
* **Encryption** support (secure storage)
* **Multiple instances** support (separate user-data with global data)
* **Customizable storage location**
* **High performance** because everything is **written in C++**
* **~30x faster than AsyncStorage**
* Uses [**JSI**](https://reactnative.dev/docs/the-new-architecture/landing-page#fast-javascriptnative-interfacing) and [**C++ NitroModules**](https://github.com/mrousavy/nitro) instead of the "old" Bridge
* **iOS**, **Android** and **Web** support
* Easy to use **React Hooks** API
> [!IMPORTANT]
> - **You're looking at MMKV V4. If you're still on V3, check out the [V3 docs here](./README_V3.md)**!
> - react-native-mmkv **V4** is now a [Nitro Module](https://nitro.margelo.com). See the [V4 Upgrade Guide](./docs/V4_UPGRADE_GUIDE.md) for more information.
## Benchmark
[StorageBenchmark](https://github.com/mrousavy/StorageBenchmark) compares popular storage libraries against each other by reading a value from storage for 1000 times:
MMKV vs other storage libraries: Reading a value from Storage 1000 times.
Measured in milliseconds on an iPhone 11 Pro, lower is better.
## Installation
### React Native
```sh
npm install react-native-mmkv react-native-nitro-modules
cd ios && pod install
```
### Expo
```sh
npx expo install react-native-mmkv react-native-nitro-modules
npx expo prebuild
```
## Usage
### Create a new instance
To create a new instance of the MMKV storage, use the `MMKV` constructor. It is recommended that you re-use this instance throughout your entire app instead of creating a new instance each time, so `export` the `storage` object.
#### Default
```ts
import { createMMKV } from 'react-native-mmkv'
export const storage = createMMKV()
```
This creates a new storage instance using the default MMKV storage ID (`mmkv.default`).
#### App Groups or Extensions
If you want to share MMKV data between your app and other apps or app extensions in the same group, open `Info.plist` and create an `AppGroupIdentifier` key with your app group's value. MMKV will then automatically store data inside the app group which can be read and written to from other apps or app extensions in the same group by making use of MMKV's multi processing mode.
See [Configuring App Groups](https://developer.apple.com/documentation/xcode/configuring-app-groups).
#### Customize
```ts
import { createMMKV } from 'react-native-mmkv'
export const storage = createMMKV({
id: `user-${userId}-storage`,
path: `${USER_DIRECTORY}/storage`,
encryptionKey: 'hunter2',
encryptionType: 'AES-256',
mode: 'multi-process',
readOnly: false,
compareBeforeSet: false,
})
```
This creates a new storage instance using a custom MMKV storage ID. By using a custom storage ID, your storage is separated from the default MMKV storage of your app.
The following values can be configured:
* `id`: The MMKV instance's ID. If you want to use multiple instances, use different IDs. For example, you can separate the global app's storage and a logged-in user's storage. (required if `path` or `encryptionKey` fields are specified, otherwise defaults to: `'mmkv.default'`)
* `path`: The MMKV instance's root path. By default, MMKV stores file inside `$(Documents)/mmkv/`. You can customize MMKV's root directory on MMKV initialization (documentation: [iOS](https://github.com/Tencent/MMKV/wiki/iOS_advance#customize-location) / [Android](https://github.com/Tencent/MMKV/wiki/android_advance#customize-location))
* `encryptionKey`: The MMKV instance's encryption/decryption key. By default, MMKV stores all key-values in plain text on file, relying on iOS's/Android's sandbox to make sure the file is encrypted. Should you worry about information leaking, you can choose to encrypt MMKV. (documentation: [iOS](https://github.com/Tencent/MMKV/wiki/iOS_advance#encryption) / [Android](https://github.com/Tencent/MMKV/wiki/android_advance#encryption))
* `encryptionType`: The MMKV instance's encryption/decryption algorithm. By default, AES-128 encryption will be used, but you can switch to AES-256 for advanced security.
* `mode`: The MMKV's process behaviour - when set to `multi-process`, the MMKV instance will assume data can be changed from the outside (e.g. App Clips, Extensions or App Groups).
* `readOnly`: Whether this MMKV instance should be in read-only mode. This is typically more efficient and avoids unwanted writes to the data if not needed. Any call to `set(..)` will throw.
* `compareBeforeSet`: Whether this MMKV instance will compare values for equality before writing them to disk. By default this is disabled, enabling it might improve performance if values are repeatedly written to disk, even if they are already persisted.
### Set
```ts
storage.set('user.name', 'Marc')
storage.set('user.age', 21)
storage.set('is-mmkv-fast-asf', true)
```
### Get
```ts
const username = storage.getString('user.name') // 'Marc'
const age = storage.getNumber('user.age') // 21
const isMmkvFastAsf = storage.getBoolean('is-mmkv-fast-asf') // true
```
### Hooks
```ts
const [username, setUsername] = useMMKVString('user.name')
const [age, setAge] = useMMKVNumber('user.age')
const [isMmkvFastAsf, setIsMmkvFastAsf] = useMMKVBoolean('is-mmkv-fast-asf')
```
### Keys
```ts
// checking if a specific key exists
const hasUsername = storage.contains('user.name')
// getting all keys
const keys = storage.getAllKeys() // ['user.name', 'user.age', 'is-mmkv-fast-asf']
// delete a specific key + value
const wasRemoved = storage.remove('user.name')
// delete all keys
storage.clearAll()
```
### Objects
```ts
const user = {
username: 'Marc',
age: 21
}
// Serialize the object into a JSON string
storage.set('user', JSON.stringify(user))
// Deserialize the JSON string into an object
const jsonUser = storage.getString('user') // { 'username': 'Marc', 'age': 21 }
const userObject = JSON.parse(jsonUser)
```
### Encryption
```ts
// encrypt all data with a private key using AES-128
storage.encrypt('hunter2')
// encrypt all data with a private key using AES-256
storage.encrypt('hunter2again', 'AES-256')
// remove encryption
storage.decrypt()
```
### Buffers
```ts
const buffer = new ArrayBuffer(3)
const dataWriter = new Uint8Array(buffer)
dataWriter[0] = 1
dataWriter[1] = 100
dataWriter[2] = 255
storage.set('someToken', buffer)
const buffer = storage.getBuffer('someToken')
console.log(buffer) // [1, 100, 255]
```
### Size
```ts
// get size of MMKV storage in bytes
const size = storage.size
if (size >= 4096) {
// clean unused keys and clear memory cache
storage.trim()
}
```
### Importing all data from another MMKV instance
To import all keys and values from another MMKV instance, use `importAllFrom(...)`:
```ts
const storage = createMMKV(...)
const otherStorage = createMMKV(...)
const importedCount = storage.importAllFrom(otherStorage)
```
### Check if an MMKV instance exists
To check if an MMKV instance exists, use `existsMMKV(...)`:
```ts
import { existsMMKV } from 'react-native-mmkv'
const exists = existsMMKV('my-instance')
```
### Delete an MMKV instance
To delete an MMKV instance, use `deleteMMKV(...)`:
```ts
import { deleteMMKV } from 'react-native-mmkv'
const wasDeleted = deleteMMKV('my-instance')
```
### Log Level
By default, MMKV logs at `Debug` level in debug builds and `Warning` level in release builds. You can override this at build time to control the verbosity of MMKV's native logs.
| Value | Level |
|-------|-------|
| 0 | Debug |
| 1 | Info |
| 2 | Warning |
| 3 | Error |
| 4 | None |
#### Android
Set `MMKV_logLevel` in your app's `android/gradle.properties`:
```properties
MMKV_logLevel=4
```
#### iOS
Set `$MMKVLogLevel` in your app's `ios/Podfile`, then run `pod install`:
```ruby
$MMKVLogLevel = 4
```
Or use an environment variable during `pod install`:
```sh
MMKV_LOG_LEVEL=4 pod install
```
## Testing with Jest or Vitest
A mocked MMKV instance is automatically used when testing with Jest or Vitest, so you will be able to use `createMMKV()` as per normal in your tests. Refer to [`example/__tests__/MMKV.harness.ts`](example/__tests__/MMKV.harness.ts) for an example using Jest.
## Documentation
* [Hooks](./docs/HOOKS.md)
* [Value-change Listeners](./docs/LISTENERS.md)
* [Migrate from AsyncStorage](./docs/MIGRATE_FROM_ASYNC_STORAGE.md)
* [Using MMKV with redux-persist](./docs/WRAPPER_REDUX.md)
* [Using MMKV with recoil](./docs/WRAPPER_RECOIL.md)
* [Using MMKV with mobx-persist-storage](./docs/WRAPPER_MOBX.md)
* [Using MMKV with mobx-persist](./docs/WRAPPER_MOBXPERSIST.md)
* [Using MMKV with zustand persist-middleware](./docs/WRAPPER_ZUSTAND_PERSIST_MIDDLEWARE.md)
* [Using MMKV with jotai](./docs/WRAPPER_JOTAI.md)
* [Using MMKV with react-query](./docs/WRAPPER_REACT_QUERY.md)
* [Using MMKV with Tinybase](./docs/WRAPPER_TINYBASE.md)
* [How is this library different from **react-native-mmkv-storage**?](https://github.com/mrousavy/react-native-mmkv/issues/100#issuecomment-886477361)
## LocalStorage and In-Memory Storage (Web)
If a user chooses to disable LocalStorage in their browser, the library will automatically provide a limited in-memory storage as an alternative. However, this in-memory storage won't persist data, and users may experience data loss if they refresh the page or close their browser. To optimize user experience, consider implementing a suitable solution within your app to address this scenario.
## Limitations
- react-native-mmkv V4 requires react-native 0.74 or higher.
- react-native-mmkv V4 requires [the new architecture](https://reactnative.dev/docs/the-new-architecture/landing-page)/TurboModules to be enabled.
- Since react-native-mmkv uses JSI for synchronous native method invocations, remote debugging (e.g. with Chrome) is no longer possible. Instead, you should use [Flipper](https://fbflipper.com) or [React DevTools](https://react.dev/learn/react-developer-tools).
## Integrations
### Rozenite
Use [@rozenite/mmkv-plugin](https://www.rozenite.dev/docs/official-plugins/mmkv) to debug your MMKV storage using Rozenite.
### Reactotron
Use [reactotron-react-native-mmkv](https://www.npmjs.com/package/reactotron-react-native-mmkv) to automatically log writes to your MMKV storage using Reactotron. [See the docs for how to setup this plugin with Reactotron.](https://www.npmjs.com/package/reactotron-react-native-mmkv)
## Community Discord
[**Join the Margelo Community Discord**](https://margelo.com/discord) to chat about react-native-mmkv or other Margelo libraries.
## Adopting at scale
react-native-mmkv is provided _as is_, I work on it in my free time.
If you're integrating react-native-mmkv in a production app, consider [funding this project](https://github.com/sponsors/mrousavy) and contact me to receive premium enterprise support, help with issues, prioritize bugfixes, request features, help at integrating react-native-mmkv, and more.
## Contributing
See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.
## License
MIT
================================================
FILE: README_V3.md
================================================
| [V4 Docs](./README.md) | **old V3 Docs** |
|:---|:---|
MMKV
The fastest key/value storage for React Native.
* **MMKV** is an efficient, small mobile key-value storage framework developed by WeChat. See [Tencent/MMKV](https://github.com/Tencent/MMKV) for more information
* **react-native-mmkv** is a library that allows you to easily use **MMKV** inside your React Native app through fast and direct JS bindings to the native C++ library.
## Features
* **Get** and **set** strings, booleans, numbers and ArrayBuffers
* **Fully synchronous** calls, no async/await, no Promises, no Bridge.
* **Encryption** support (secure storage)
* **Multiple instances** support (separate user-data with global data)
* **Customizable storage location**
* **High performance** because everything is **written in C++**
* **~30x faster than AsyncStorage**
* Uses [**JSI**](https://reactnative.dev/docs/the-new-architecture/landing-page#fast-javascriptnative-interfacing) and [**C++ TurboModules**](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/turbo-modules-xplat.md) instead of the "old" Bridge
* **iOS**, **Android** and **Web** support
* Easy to use **React Hooks** API
> [!IMPORTANT]
> - **You're looking at MMKV V3. If you want to upgrade to the beta, check out the [V4 docs here](./README.md)**!
> react-native-mmkv V3 is now a pure C++ TurboModule, and **requires the new architecture to be enabled**. (react-native 0.75+)
> - If you want to use react-native-mmkv 3.x.x, you need to enable the new architecture in your app (see ["Enable the New Architecture for Apps"](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/enable-apps.md))
> - For React-Native 0.74.x, use react-native-mmkv 3.0.1. For React-Native 0.75.x and higher, use react-native-mmkv 3.0.2 or higher.
> - If you cannot use the new architecture yet, downgrade to react-native-mmkv 2.x.x for now.
## Benchmark
[StorageBenchmark](https://github.com/mrousavy/StorageBenchmark) compares popular storage libraries against each other by reading a value from storage for 1000 times:
MMKV vs other storage libraries: Reading a value from Storage 1000 times.
Measured in milliseconds on an iPhone 11 Pro, lower is better.
## Installation
### React Native
```sh
yarn add react-native-mmkv
cd ios && pod install
```
### Expo
```sh
npx expo install react-native-mmkv
npx expo prebuild
```
## Usage
### Create a new instance
To create a new instance of the MMKV storage, use the `MMKV` constructor. It is recommended that you re-use this instance throughout your entire app instead of creating a new instance each time, so `export` the `storage` object.
#### Default
```js
import { MMKV } from 'react-native-mmkv'
export const storage = new MMKV()
```
This creates a new storage instance using the default MMKV storage ID (`mmkv.default`).
#### App Groups or Extensions
If you want to share MMKV data between your app and other apps or app extensions in the same group, open `Info.plist` and create an `AppGroup` key with your app group's value. MMKV will then automatically store data inside the app group which can be read and written to from other apps or app extensions in the same group by making use of MMKV's multi processing mode.
See [Configuring App Groups](https://developer.apple.com/documentation/xcode/configuring-app-groups).
#### Customize
```js
import { MMKV, Mode } from 'react-native-mmkv'
export const storage = new MMKV({
id: `user-${userId}-storage`,
path: `${USER_DIRECTORY}/storage`,
encryptionKey: 'hunter2',
mode: Mode.MULTI_PROCESS,
readOnly: false
})
```
This creates a new storage instance using a custom MMKV storage ID. By using a custom storage ID, your storage is separated from the default MMKV storage of your app.
The following values can be configured:
* `id`: The MMKV instance's ID. If you want to use multiple instances, use different IDs. For example, you can separate the global app's storage and a logged-in user's storage. (required if `path` or `encryptionKey` fields are specified, otherwise defaults to: `'mmkv.default'`)
* `path`: The MMKV instance's root path. By default, MMKV stores file inside `$(Documents)/mmkv/`. You can customize MMKV's root directory on MMKV initialization (documentation: [iOS](https://github.com/Tencent/MMKV/wiki/iOS_advance#customize-location) / [Android](https://github.com/Tencent/MMKV/wiki/android_advance#customize-location))
* `encryptionKey`: The MMKV instance's encryption/decryption key. By default, MMKV stores all key-values in plain text on file, relying on iOS's/Android's sandbox to make sure the file is encrypted. Should you worry about information leaking, you can choose to encrypt MMKV. (documentation: [iOS](https://github.com/Tencent/MMKV/wiki/iOS_advance#encryption) / [Android](https://github.com/Tencent/MMKV/wiki/android_advance#encryption))
* `mode`: The MMKV's process behaviour - when set to `MULTI_PROCESS`, the MMKV instance will assume data can be changed from the outside (e.g. App Clips, Extensions or App Groups).
* `readOnly`: Whether this MMKV instance should be in read-only mode. This is typically more efficient and avoids unwanted writes to the data if not needed. Any call to `set(..)` will throw.
### Set
```js
storage.set('user.name', 'Marc')
storage.set('user.age', 21)
storage.set('is-mmkv-fast-asf', true)
```
### Get
```js
const username = storage.getString('user.name') // 'Marc'
const age = storage.getNumber('user.age') // 21
const isMmkvFastAsf = storage.getBoolean('is-mmkv-fast-asf') // true
```
### Hooks
```js
const [username, setUsername] = useMMKVString('user.name')
const [age, setAge] = useMMKVNumber('user.age')
const [isMmkvFastAsf, setIsMmkvFastAf] = useMMKVBoolean('is-mmkv-fast-asf')
```
### Keys
```js
// checking if a specific key exists
const hasUsername = storage.contains('user.name')
// getting all keys
const keys = storage.getAllKeys() // ['user.name', 'user.age', 'is-mmkv-fast-asf']
// delete a specific key + value
storage.delete('user.name')
// delete all keys
storage.clearAll()
```
### Objects
```js
const user = {
username: 'Marc',
age: 21
}
// Serialize the object into a JSON string
storage.set('user', JSON.stringify(user))
// Deserialize the JSON string into an object
const jsonUser = storage.getString('user') // { 'username': 'Marc', 'age': 21 }
const userObject = JSON.parse(jsonUser)
```
### Encryption
```js
// encrypt all data with a private key
storage.recrypt('hunter2')
// remove encryption
storage.recrypt(undefined)
```
### Buffers
```js
const buffer = new ArrayBuffer(3)
const dataWriter = new Uint8Array(buffer)
dataWriter[0] = 1
dataWriter[1] = 100
dataWriter[2] = 255
storage.set('someToken', buffer)
const buffer = storage.getBuffer('someToken')
console.log(buffer) // [1, 100, 255]
```
### Size
```js
// get size of MMKV storage in bytes
const size = storage.size
if (size >= 4096) {
// clean unused keys and clear memory cache
storage.trim()
}
```
## Testing with Jest or Vitest
A mocked MMKV instance is automatically used when testing with Jest or Vitest, so you will be able to use `new MMKV()` as per normal in your tests. Refer to [package/example/test/MMKV.test.ts](package/example/test/MMKV.test.ts) for an example using Jest.
## Documentation
* [Hooks](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/HOOKS.md)
* [Value-change Listeners](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/LISTENERS.md)
* [Migrate from AsyncStorage](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/MIGRATE_FROM_ASYNC_STORAGE.md)
* [Using MMKV with redux-persist](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/WRAPPER_REDUX.md)
* [Using MMKV with recoil](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/WRAPPER_RECOIL.md)
* [Using MMKV with mobx-persist-storage](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/WRAPPER_MOBX.md)
* [Using MMKV with mobx-persist](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/WRAPPER_MOBXPERSIST.md)
* [Using MMKV with zustand persist-middleware](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/WRAPPER_ZUSTAND_PERSIST_MIDDLEWARE.md)
* [Using MMKV with jotai](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/WRAPPER_JOTAI.md)
* [Using MMKV with react-query](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/WRAPPER_REACT_QUERY.md)
* [Using MMKV with Tinybase](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/WRAPPER_TINYBASE.md)
* [How is this library different from **react-native-mmkv-storage**?](https://github.com/mrousavy/react-native-mmkv/issues/100#issuecomment-886477361)
## LocalStorage and In-Memory Storage (Web)
If a user chooses to disable LocalStorage in their browser, the library will automatically provide a limited in-memory storage as an alternative. However, this in-memory storage won't persist data, and users may experience data loss if they refresh the page or close their browser. To optimize user experience, consider implementing a suitable solution within your app to address this scenario.
## Limitations
- react-native-mmkv V3 requires react-native 0.74 or higher.
- react-native-mmkv V3 requires [the new architecture](https://reactnative.dev/docs/the-new-architecture/landing-page)/TurboModules to be enabled.
- Since react-native-mmkv uses JSI for synchronous native method invocations, remote debugging (e.g. with Chrome) is no longer possible. Instead, you should use [Flipper](https://fbflipper.com) or [React DevTools](https://react.dev/learn/react-developer-tools).
## Integrations
### Flipper
Use [flipper-plugin-react-native-mmkv](https://github.com/muchobien/flipper-plugin-react-native-mmkv) to debug your MMKV storage using Flipper. You can also simply `console.log` an MMKV instance.
### Reactotron
Use [reactotron-react-native-mmkv](https://www.npmjs.com/package/reactotron-react-native-mmkv) to automatically log writes to your MMKV storage using Reactotron. [See the docs for how to setup this plugin with Reactotron.](https://www.npmjs.com/package/reactotron-react-native-mmkv)
## Community Discord
[**Join the Margelo Community Discord**](https://margelo.com/discord) to chat about react-native-mmkv or other Margelo libraries.
## Adopting at scale
react-native-mmkv is provided _as is_, I work on it in my free time.
If you're integrating react-native-mmkv in a production app, consider [funding this project](https://github.com/sponsors/mrousavy) and contact me to receive premium enterprise support, help with issues, prioritize bugfixes, request features, help at integrating react-native-mmkv, and more.
## Contributing
See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.
## License
MIT
================================================
FILE: babel.config.js
================================================
module.exports = {
presets: ['module:@react-native/babel-preset'],
env: {
test: {
presets: [
['@babel/preset-env', { targets: { node: 'current' } }],
['@babel/preset-react', { runtime: 'automatic' }],
'@babel/preset-typescript'
]
}
}
}
================================================
FILE: bunfig.toml
================================================
[test]
# Configure bun test to only run tests in specific directories
# This prevents bun test from interfering with Jest tests
root = "packages/react-native-mmkv/__bun_tests__"
[install]
# Opt out from isolated installs
linker = "hoisted"
================================================
FILE: docs/HOOKS.md
================================================
# Hooks
react-native-mmkv provides an easy to use React-Hooks API to be used in Function Components.
## Reactively use individual keys
```tsx
function App() {
const [username, setUsername] = useMMKVString("user.name")
const [age, setAge] = useMMKVNumber("user.age")
const [isPremiumUser, setIsPremiumUser] = useMMKVBoolean("user.isPremium")
const [privateKey, setPrivateKey] = useMMKVBuffer("user.privateKey")
}
```
## Clear a key
```tsx
function App() {
const [username, setUsername] = useMMKVString("user.name")
// ...
const onLogout = useCallback(() => {
setUsername(undefined)
}, [])
}
```
## Objects
```tsx
type User = {
id: string
username: string
age: number
}
function App() {
const [user, setUser] = useMMKVObject("user")
}
```
## Reactively use an MMKV Instance
```tsx
function App() {
const storage = useMMKV()
// ...
const onLogin = useCallback((username) => {
storage.set("user.name", "Marc")
}, [storage])
}
```
## Reactively use individual keys from custom instances
```tsx
function App() {
const globalStorage = useMMKV()
const userStorage = useMMKV({ id: `${userId}.storage` })
const [username, setUsername] = useMMKVString("user.name", userStorage)
}
```
## Listen to value changes
```tsx
function App() {
useMMKVListener((key) => {
console.log(`Value for "${key}" changed!`)
})
}
```
## Listen to value changes on a specific instance
```tsx
function App() {
const storage = useMMKV({ id: `${userId}.storage` })
useMMKVListener((key) => {
console.log(`Value for "${key}" changed in user storage!`)
}, storage)
}
```
## Listen to all keys in an instance
```tsx
function App() {
const storage = useMMKV()
const keys = useMMKVKeys(storage)
}
```
================================================
FILE: docs/LISTENERS.md
================================================
# Listeners
MMKV instances also contain an observer/listener registry.
### Add a listener when a `key`'s `value` changes.
```ts
const storage = createMMKV()
const listener = storage.addOnValueChangedListener((changedKey) => {
const newValue = storage.getString(changedKey)
console.log(`"${changedKey}" new value: ${newValue}`)
})
```
Don't forget to remove the listener when no longer needed. For example, when the user logs out:
```ts
function SettingsScreen() {
// ...
const onLogout = useCallback(() => {
// ...
listener.remove()
}, [])
// ...
}
```
================================================
FILE: docs/MIGRATE_FROM_ASYNC_STORAGE.md
================================================
# Migrate from AsyncStorage
Here's a migration script to copy all values from AsyncStorage to MMKV, and delete them from AsyncStorage afterwards.
storage.ts
```ts
import AsyncStorage from '@react-native-async-storage/async-storage';
import { createMMKV } from 'react-native-mmkv';
export const storage = createMMKV();
// TODO: Remove `hasMigratedFromAsyncStorage` after a while (when everyone has migrated)
export const hasMigratedFromAsyncStorage = storage.getBoolean(
'hasMigratedFromAsyncStorage',
);
// TODO: Remove `hasMigratedFromAsyncStorage` after a while (when everyone has migrated)
export async function migrateFromAsyncStorage(): Promise {
console.log('Migrating from AsyncStorage -> MMKV...');
const start = global.performance.now();
const keys = await AsyncStorage.getAllKeys();
for (const key of keys) {
try {
const value = await AsyncStorage.getItem(key);
if (value != null) {
if (['true', 'false'].includes(value)) {
storage.set(key, value === 'true');
} else {
storage.set(key, value);
}
AsyncStorage.removeItem(key);
}
} catch (error) {
console.error(
`Failed to migrate key "${key}" from AsyncStorage to MMKV!`,
error,
);
throw error;
}
}
storage.set('hasMigratedFromAsyncStorage', true);
const end = global.performance.now();
console.log(`Migrated from AsyncStorage -> MMKV in ${end - start}ms!`);
}
```
App.tsx
```tsx
...
import { hasMigratedFromAsyncStorage, migrateFromAsyncStorage } from './storage';
...
export default function App() {
// TODO: Remove `hasMigratedFromAsyncStorage` after a while (when everyone has migrated)
const [hasMigrated, setHasMigrated] = useState(hasMigratedFromAsyncStorage);
...
useEffect(() => {
if (!hasMigratedFromAsyncStorage) {
InteractionManager.runAfterInteractions(async () => {
try {
await migrateFromAsyncStorage()
setHasMigrated(true)
} catch (e) {
// TODO: fall back to AsyncStorage? Wipe storage clean and use MMKV? Crash app?
}
});
}
}, []);
if (!hasMigrated) {
// show loading indicator while app is migrating storage...
return (
);
}
return (
);
}
```