mrousavy / react-native-mmkv

⚡️ The fastest key/value storage for React Native. ~30x faster than AsyncStorage!
MIT License
5.52k stars 238 forks source link
android cpp database fast hacktoberfest ios jni jsi localstorage mmkv native-module react react-native storage turbomodule

react-native-mmkv

MMKV

The fastest key/value storage for React Native.



This library helped you? Consider sponsoring!


Features

react-native-mmkv V3

[!IMPORTANT] react-native-mmkv V3 is now a pure C++ TurboModule, and requires the new architecture to be enabled.

  • 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")
  • If you cannot use the new architecture yet, downgrade to react-native-mmkv 2.x.x for now.

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

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.

Customize

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

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:

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

Hooks

const [username, setUsername] = useMMKVString('user.name')
const [age, setAge] = useMMKVNumber('user.age')
const [isMmkvFastAsf, setIsMmkvFastAf] = useMMKVBoolean('is-mmkv-fast-asf')

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

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

// 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 for an example using Jest.

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

Integrations

Flipper

Use 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 to automatically log writes to your MMKV storage using Reactotron. See the docs for how to setup this plugin with Reactotron.

Community Discord

Join the Margelo Community 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 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