All Guides Setting up Zustand Store with React Native MMKV

Setting up Zustand Store with React Native MMKV

Zustand and React Native MMKV can be a powerful combination for persisting data in React Native. Let's get started and integrate Zustand to make use of this library.

Install Zustand and React Native MMKV

Make sure to install both libraries by running the following command.

npx expo install zustand react-native-mmkv 

Create Zustand Store

// @/store/ZustandStore.tsx

import {MMKV} from "react-native-mmkv";

export const storage = new MMKV();

export default {
    setItem: (name, value) => {
        return storage.set(name, value);
    },
    getItem: (name) => {
        const value = storage.getString(name);
        return value ?? null;
    },
    removeItem: (name) => {
        return storage.delete(name);
    },
}

Create a User Store and Persist using MMKV

import {create} from 'zustand'
import {createJSONStorage, persist} from 'zustand/middleware'
import ZustandStore from "../services/ZustandStore";

export type UserState = {
    name: string,
    email: string,
}

export type UserStore = {
    user: UserState,
}

export default create<UserStore>()(
    persist(
        (set, get) => ({
            user: {
                name: '',
                email: '',
            },
            setUser: () => {
                set({
                    user: {
                        name: 'John',
                        email: '[email protected]',
                    },
                });
            }
        }),
        {
            name: 'user',
            storage: createJSONStorage(() => ZustandStore),
        }
    )
)

That's it, explore HestiaKit App Screens and get your dream app up and running in hours.

Introducing NeNews React Native UI Kit

HestiaKit Premium

You have to be signed in to favorite this screen

Share

HestiaKit Premium

This is HestiaKit premium component