Cách Duy Trì Cửa Hàng Redux Của Bạn

Redux persist is a library allowing to save the redux store in the local storage of your browser.Bạn đang xem: Redux-persist là gì

But, using redux-persist and changing the store"s architecture could trigger issues. This article illustrates, with a basic example, how persistence works with your Redux store, then focus on the persisted store"s transformation across code versions and app uses.

Bạn đang xem: Cách duy trì cửa hàng redux của bạn

To install it in your project, I recommend you read the documentation or this article.

How to persist a store and how it works

Let"s take, as an example, this redux store from a React project, generated with create-react-app:


There is:

a debounced input with current value = inputValuea button GO submitting inputValue in store as key confirmedMessagea persisted field named number in redux counting the number of submissions made.

I implemented redux-persist as explained in the official doc and my store. You can find all the code in this repo.


There is a custom function persist(), to define in persistConfig only what"s changed for this article.

Steps of persistence:


While visiting the app, the redux store is created as the initial state given through the reducers. This defines the first content of your app, and persistence has not done its job yet.

Xem thêm: Đăng Nhập Facebook Phiên Bản Cũ Archives, Facebook Phiên Bản Cũ


During persist step, in every persisted store, an object is added with this configuration:



INIT: initial state set the form I need

persist/PERSIST: _persist object is added with rehydrated false

persist/REHYDRATE: persisted data replace the Redux store.

What went wrong here?

The variable "number", which is supposed to have the structure of the new version of the app, is replaced by the old persisted structure. You lose all your store changes.

This inconsistency can jeopardize the use of your code if you don"t anticipate them.

Handling it with a version-controlled store.

To do this, use the function createMigrate() and pass in the persistConfig object in migrate" key:

Migrations are applied on your state before replacing your store data in REHYDRATE step.

If your storage comes from the store in version -1, which is the default version, and you deploy version 0 in your app, the migration 0 will be applied on storage state at every user"s connexion:

For example, with this definition of the passed migrations, your state will be reset as the initial state and you will have the expected behaviour during REHYDRATE: