Persist and rehydrate a redux store.
npm i --save redux-persist
Basic usage requires adding a few lines to a traditional redux application:
// add `autoRehydrate` as an enhancer to your store (note: `autoRehydrate` is not a middleware)const store =// begin periodically persisting the store
For per reducer rehydration logic, you can opt-in by adding a handler to your reducer:
//...case REHYDRATE:var incoming = actionpayloadmyReducerif incoming return ...state ...incoming specialKey:return state
You may also need to configure the persistence layer, or take action after rehydration has completed:
And if things get out of wack, just purge the storage
persistStore(store, [config, callback])
serial:true, incoming should be a string, that will be deserialized and passed through the transforms defined in the persistor.
import * as constants from 'redux-persist/constants'. This includes
If you need more control over persistence flow, you can implement
createPersistor. For example you can skip autoRehydrate and directly pass restoredState into your store as initialState:
const persistConfig = /* ... */
const persistor = // persistStore restores and persistsconst secondaryPersistor = // createPersistor only persists
// sessionStorage// react-native// web with recommended localForage
Transforms allow for arbitrary state transforms before saving and during rehydration.
let myTransform =
One challenge developers encounter when persisting state for the first time is what happens when the shape of the application state changes between deployments? Solution: redux-persist-migrate
A common mistake is to fire actions that modify state before rehydration is complete which then will be overwritten by the rehydrate action. You can either defer firing of those actions until rehydration is complete, or you can use an action buffer.
Because persisting state is inherently stateful,
persistStore lives outside of the redux store. Importantly this keeps the store 'pure' and makes testing and extending the persistor much easier.
autoRehydrate is a store enhancer that automatically rehydrates state.
While auto rehydration works out of the box, individual reducers can opt in to handling their own rehydration, allowing for more complex operations like data transforms and cache invalidation. Simply define a handler for the rehydrate action in your reducer, and if the state is mutated, auto rehydrate will skip that key.
Auto rehydrate is provided as a convenience. In a large application, or one with atypical reducer composition, auto rehydration may not be convenient. In this case, simply omit autoRehydrate. Rehydration actions will still be fired by
persistStore, and can then be handled individually by reducers or using a custom rehydration handler.