To persist Jotai atoms using MMKV, you must implement a custom atomWithMMKV function. This function leverages Jotai's atomWithStorage and createJSONStorage utilities, wrapping MMKV's getString, set, remove, and addOnValueChangedListener methods.
createJSONStorage automatically handles JSON.stringify() when saving and JSON.parse() when retrieving values, allowing you to store complex objects directly.
Once implemented, use atomWithMMKV(key, initialValue) instead of the standard atom(initialValue) to ensure the state persists across app restarts.
import { atomWithStorage, createJSONStorage } from 'jotai/utils';
import { createMMKV } from 'react-native-mmkv';
const storage = createMMKV();
function getItem(key: string): string | null {
const value = storage.getString(key)
return value ? value : null
}
function setItem(key: string, value: string): void {
storage.set(key, value)
}
function removeItem(key: string): void {
storage.remove(key);
}
function subscribe(
key: string,
callback: (value: string | null) => void
): () => void {
const listener = (changedKey: string) => {
if (changedKey === key) {
callback(getItem(key))
}
}
const { remove } = storage.addOnValueChangedListener(listener)
return () => {
remove()
}
}
export const atomWithMMKV = <T>(key: string, initialValue: T) =>
atomWithStorage<T>(
key,
initialValue,
createJSONStorage<T>(() => ({
getItem,
setItem,
removeItem,
subscribe,
})),
{ getOnInit: true }
);
// Usage:
const myAtom = atomWithMMKV('my-atom-key', 'value');