LoginSignup
56
45

More than 5 years have passed since last update.

Redux Persistのススメ

Posted at

Redux Persistとは

storeを永続化してくれるライブラリです。

メリットは、

  • 簡単な設定でstoreの永続化ができる
  • autoRehydrateという機能があり、localStorage/localForageなどのローカルDBに自動で永続化し、それをアプリ起動時に読み込んでくれる

という感じで、storeの永続化をどうしようかと悩んでいる人にとって最高のライブラリだと思います!

使い方

ざっくり下のようにstore作成部分を書くと、

  • 全てのreducerのstateが永続化される
  • 自動でautoRehydrateアクションが実行される
    • reducerが実行されるたび永続化され、アプリ起動時に永続化されたデータを読み込む

ようになります。

import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { persistStore, autoRehydrate } from 'redux-persist';
import localforage from 'localforage';
import * as reducers from '../reducers/index';

const loggerMiddleware = createLogger();

export default function configureStore(initialState) {
  const store = createStore(
    combineReducers({
      ...reducers,
    }),
    initialState,
    compose(
      applyMiddleware(
        thunkMiddleware
      ),
      autoRehydrate()
    )
  );
  persistStore(store, {storage: localforage}, () => {
    console.log('autoRehydrate completed');
  });

  return store;
}

さっくりとした各要素の説明

autoRehydrate関数

store用のエンハンサーです。これ単体をcreateStoreの第三引数に渡しても動作しますが、他にもエンハンサーがある場合はcompose関数で合成してください。

persistStore関数

こいつにstoreを渡して永続化を走らせるようにします。2つ目の引数は色々とオプションを渡すことができて、{storage: localforage}のようにストレージを指定することが出来ます。(何も指定しないとlocalStorageになるっぽい)
3つめの引数は、autoRehydrateが完了した時に呼び出されるコールバックで、適当なログ出力等させてください。

まとめ

こういうの欲しかった!感がすごいです。reducerごとに永続化させる・させない等のオプションも指定できたりと機能も豊富なので、もう少し使い込んだらまた記事アップデートします。

56
45
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
56
45