• Stars
    star
    4,903
  • Rank 8,063 (Top 0.2 %)
  • Language
    C++
  • License
    Other
  • Created about 3 years ago
  • Updated 22 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

⚡️ The fastest key/value storage for React Native. ~30x faster than AsyncStorage!

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 for more information
  • react-native-mmkv is a library that allows you to easily use MMKV inside your React Native applications. It provides fast and direct bindings to the native C++ library which are accessible through a simple JS API.

Features

  • Get and set strings, booleans and numbers
  • Fully synchronous calls, no async/await, no Promises, no Bridge.
  • Encryption support (secure storage)
  • Multiple instances support (separate user-data with global data)
  • Customize storage location
  • High performance because everything is written in C++
  • ~30x faster than AsyncStorage
  • Uses JSI instead of the "old" Bridge
  • iOS, Android and Web support
  • Easy to use React Hooks API

Sponsors

react-native-mmkv is sponsored by getstream.io.
Try the React Native Chat tutorial 💬

Benchmark

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

yarn add react-native-mmkv
cd ios && pod install

Expo

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

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).

Customize

import { MMKV } from 'react-native-mmkv'

export const storage = new MMKV({
  id: `user-${userId}-storage`,
  path: `${USER_DIRECTORY}/storage`,
  encryptionKey: 'hunter2'
})

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 / Android)
  • 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 / Android)

Set

storage.set('user.name', 'Marc')
storage.set('user.age', 21)
storage.set('is-mmkv-fast-asf', true)

Get

const username = storage.getString('user.name') // 'Marc'
const age = storage.getNumber('user.age') // 21
const isMmkvFastAsf = storage.getBoolean('is-mmkv-fast-asf') // true

Keys

// 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

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

// encrypt all data with a private key
storage.recrypt('hunter2')

// remove encryption
storage.recrypt(undefined)

Buffers

storage.set('someToken', new Uint8Array([1, 100, 255]))
const buffer = storage.getBuffer('someToken')
console.log(buffer) // [1, 100, 255]

Testing with Jest

A mocked MMKV instance is automatically used when testing with Jest, so you will be able to use new MMKV() as per normal in your tests. Refer to example/test/MMKV.test.ts for an example.

Documentation

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

As the library uses JSI for synchronous native methods access, remote debugging (e.g. with Chrome) is no longer possible. Instead, you should use Flipper.

Debugging

Use flipper-plugin-react-native-mmkv to debug your MMKV storage using Flipper. You can also simply console.log an MMKV instance.

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 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 to learn how to contribute to the repository and the development workflow.

License

MIT

More Repositories

1

react-native-vision-camera

📸 A powerful, high-performance React Native Camera library.
Swift
6,320
star
2

react-native-blurhash

🖼️ A library to show colorful blurry placeholders while your content loads.
Kotlin
1,568
star
3

react-native-multithreading

🧵 Fast and easy multithreading for React Native using JSI
C++
1,049
star
4

Colorwaver

🎨 An app to detect color palettes in the real world - powered by VisionCamera
TypeScript
548
star
5

react-native-jsi-image

🖼️ A writeable in-memory Image JSI Host Object
C++
267
star
6

react-native-tracking-transparency

🕵️ A React Native Library for interacting with the tracking API from iOS 14.
Java
208
star
7

react-native-google-nearby-messages

📲 Communicate with nearby devices using Bluetooth, BLE, WiFi and near-ultrasonic audio. Broadcast and receive small payloads (like strings) using the easy-to-use React Native API!
Kotlin
173
star
8

react-native-jsi-contacts

A contacts library for React Native using JSI
C++
140
star
9

AnimatedGif

📼 A high performance .NET library for reading and creating animated GIFs
C#
127
star
10

react-native-blob-jsi-helper

A React Native library for accessing an ArrayBuffer of a Blob instance.
C++
118
star
11

react-native-jsi-library-template

Template for React Native JSI Libraries à la Marc
C++
110
star
12

clean-rn

A simple CLI tool to clean all React Native caches in your project.
JavaScript
109
star
13

vision-camera-image-labeler

VisionCamera Frame Processor Plugin to label images using MLKit Vision
Java
97
star
14

ImgurSniper

📷 A quick and easy Image, Screenshot and Screen recording sharing tool
C#
85
star
15

react-native-style-utilities

Fully typed hooks and utility functions for the React Native StyleSheet API
JavaScript
78
star
16

Hotkeys

🔤 A small C# (.NET) Library which allows binding of global HotKeys to any Application's Windows (including Windows Apps such as explorer.exe), even in Background. (using P/Invokes)
C#
71
star
17

react-native-notification-badge

🔴 A notification badge count manager for React Native
Swift
47
star
18

react-native-pressable-opacity

A <PressableOpacity> and a supercharged <NativePressableOpacity> components for React Native
TypeScript
46
star
19

GenericProtocol

⚡️ A fast TCP event based buffered server/client protocol for transferring data over the (inter)net in .NET 🌐
C#
42
star
20

DiscordMusicBot

A Discord Bot for playing YouTube music.
C#
41
star
21

react-native-pressable-scale

A <PressableScale> and a supercharged <NativePressableScale> components for React Native
TypeScript
39
star
22

StorageBenchmark

Benchmark App to compare different storage libraries (MMKV, AsyncStorage, WatermelonDB, RealmDB, SQLite)
Java
29
star
23

react-native-screen-corner-radius

📱 A React Native library to get the Device's Screen's corner radius
Java
27
star
24

BrabeNetz

🧠 A fast and clean supervised neural network in C++, capable of effectively using multiple cores
C++
26
star
25

Toast

🍞 The rounded and animated Android Toast for .NET WPF/XAML
C#
26
star
26

Fiddle

📜 A lightweight code editor for editing, compiling and running code snippets/scripts supporting multiple languages and rich GUI
C
23
star
27

Jellyfish

🐟 An incredibly lightweight and type safe MVVM library for .NET WPF, Silverlight, Xamarin and UWP
C#
20
star
28

PostShot

📷 An easy to use, lightning fast and modern screenshot and screen-recording tool powered by C++ and Qt
C++
17
star
29

vision-camera-resize-plugin

A VisionCamera Frame Processor plugin for fast buffer resizing
Objective-C
17
star
30

WebUntisSharp

⏰ A Wrapper of the WebUntis JSON API for .NET
C#
14
star
31

pipestate

🏦 A minimal state management library for React.
TypeScript
13
star
32

gimp-rpc

A GIMP plugin to display Discord Rich Presence made with C
C
11
star
33

react-native-sectioned-slider

An iOS 11 Control Center inspired Slider for React Native
Ruby
10
star
34

ClipboardMonitor

A small C# Library for Monitoring Clipboard with P/Invokes (e.g.: Clipboard Content Changed event)
C#
9
star
35

GameFinder

🎮 An application for finding games to play you and your friends have on Steam
C#
8
star
36

QHotkeys

🔠 A small and lightweight cross platform C++ library implementing a system-wide hotkey system for Qt
C++
7
star
37

Keepr

A Tinder-like swipe view to keep or remove pictures from a photoshoot with extra comparison features
TypeScript
7
star
38

BmpPwd

🔐 BmpPwd is a .NET Class Library for overloadable en/decrypting strings or binary data to a System.Drawing.Image
C#
7
star
39

MaterialDesignWindowsDialogs

A new Theme (Android Material Design) for Windows Message Boxes (by hooking)
C#
7
star
40

shared-registry

Shared-Registry allows you to share objects between instances without introducing memory leaks.
TypeScript
6
star
41

dotfiles

My personal minimalistic dotfiles (.vimrc, .zshrc, .oh-my.zsh, custom scripts, ..)
Shell
6
star
42

mrousavy

✨ it's lit ✨
6
star
43

MetaLog

📝 Simple, yet effective, logging with Metadata CallerInfo for creating beautiful Log files in C#/VB .NET
C#
5
star
44

SchoolTool

📓 An App to watch your timetable and get notified of changes.
C#
3
star
45

HankHill

A discord bot for pixelating and jpegifying images
C#
3
star
46

maconvert

Easily convert .svg files to .png files
JavaScript
3
star
47

TinyRocket

A 2D Endless Unity Game; Fly up high and beat highscores with your customizable and upgradeable Rocket!
C#
3
star
48

Cirilla

🤖 Cirilla - The swiss army knife discord bot supporting many commands and systems
C#
3
star
49

Morph

🛠 A fast .NET Standard Class Library for parsing results from an SQL query to .NET objects to eliminate risky column-index hardcoding
C#
2
star
50

QPastebin

A quick Pastebin-uploader shell script using curl and the Pastebin REST API
Shell
2
star
51

QuantumSnippets

Snippets, Examples or Test code for Quantum Computers written in the Microsoft Quantum Computer Programming Language Q#
C#
1
star
52

discord-cli

CLI for discord bots
JavaScript
1
star
53

ModellbaumesseRoboter

Roboter für Modellbaumesse 2016 (TGM 3DHIT)
C++
1
star
54

Vertaler

📖 A pop-up tray application to instantly translate something from your clipboard using Google Translate
C#
1
star
55

pokecord-guesser

Guesser for Pokecord using Discord API and reverse image lookup
HTML
1
star
56

VisionCameraDemo

Demo for using VisionCamera + zooming
TypeScript
1
star
57

ModWnd

👺 A daemon to move any Window from within it's body (child area) while holding a modifier key (Windows/Alt)
C++
1
star