If you want to use MMKV with Jotai, create the following atomWithMMKV function:
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 }
);Then simply use atomWithMMKV(..) instead of atom(..) when creating an atom you'd like to persist accross app starts.
const myAtom = atomWithMMKV('my-atom-key', 'value');Note: createJSONStorage handles JSON.stringify()/JSON.parse() when setting and returning the stored value.
See the official Jotai doc here: https://jotai.org/docs/utils/atom-with-storage