DEV Community

Cover image for Efficiently Persisting State in React Native with Recoil and react-native-mmkv
HidetoshiYanagisawa
HidetoshiYanagisawa

Posted on

Efficiently Persisting State in React Native with Recoil and react-native-mmkv

Introduction

Recoil has gained traction as a state management library for React. However, there are various methods to persist its state. In this article, we'll explore how to efficiently persist Recoil's state using react-native-mmkv, a fast key-value storage.

Installing Necessary Packages

First, let's install the required packages:

yarn add recoil react-native-mmkv
Enter fullscreen mode Exit fullscreen mode

Then, link the native part of react-native-mmkv:

expo install react-native-mmkv
Enter fullscreen mode Exit fullscreen mode

Creating a Persistence Helper for Recoil

Next, we'll create a helper function to persist the state of Recoil's atoms and selectors using react-native-mmkv.

import MMKV from 'react-native-mmkv';
import { atom, DefaultValue } from 'recoil';

export const persistentAtom = <T>(key: string, defaultVal: T) => {
  return atom<T>({
    key,
    default: defaultVal,
    effects_UNSTABLE: [
      ({ setSelf, onSet }) => {
        const savedValue = MMKV.getString(key);

        if (savedValue != null) {
          setSelf(JSON.parse(savedValue));
        }

        onSet((newValue) => {
          if (newValue instanceof DefaultValue) {
            MMKV.delete(key);
          } else {
            MMKV.set(key, JSON.stringify(newValue));
          }
        });
      },
    ],
  });
};
Enter fullscreen mode Exit fullscreen mode

Using the Persistent Atom

Now, let's create a persisted atom using the helper function:

import { persistentAtom } from './path-to-your-helper';

export const userState = persistentAtom('userState', {
  name: '',
  age: 0,
});
Enter fullscreen mode Exit fullscreen mode

Using in Your Application

You can use this persisted atom in your application just like any regular Recoil atom:

import { useRecoilState } from 'recoil';
import { userState } from './path-to-your-atom';

const UserInfo = () => {
  const [user, setUser] = useRecoilState(userState);

  return (
    <View>
      <Text>Name: {user.name}</Text>
      <Text>Age: {user.age}</Text>
    </View>
  );
};
Enter fullscreen mode Exit fullscreen mode

Conclusion

Combining Recoil with react-native-mmkv allows for efficient state persistence in React Native applications. This combination is ideal for maintaining application performance while securely storing user data.


If you found this article helpful, please give it a thumbs up or leave a comment. Any questions or feedback are also welcome! 🚀

Top comments (0)