1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Recoilとreact-native-mmkvでデータを効率的に永続化する方法

Posted at

目次

  1. はじめに
  2. 必要なパッケージのインストール
  3. Recoilの永続化ヘルパーの作成
  4. 永続化アトムの使用
  5. アプリケーションでの使用
  6. まとめ

はじめに

RecoilはReactの状態管理ライブラリとして人気がありますが、その状態を永続化する方法はいくつかあります。この記事では、react-native-mmkvという高速なキーバリューストレージを使用して、Recoilの状態を効率的に永続化する方法を紹介します。

必要なパッケージのインストール

まず、必要なパッケージをインストールします。

yarn add recoil react-native-mmkv

そして、react-native-mmkvのネイティブ部分をリンクします。

expo install react-native-mmkv

Recoilの永続化ヘルパーの作成

次に、Recoilのアトムやセレクタの状態を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));
          }
        });
      },
    ],
  });
};

永続化アトムの使用

上記のヘルパー関数を使用して永続化されたアトムを作成します。

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

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

アプリケーションでの使用

通常のRecoilアトムと同じように、アプリケーションでこの永続化アトムを使用できます。

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

まとめ

Recoilとreact-native-mmkvを組み合わせることで、React Nativeアプリケーションの状態を効率的に永続化することができます。この組み合わせは、アプリケーションのパフォーマンスを維持しながら、ユーザーデータを安全に保存するのに適しています。


いいねやコメントがあれば、大変助かります!質問やフィードバックもお気軽にどうぞ!🚀


1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?