How to Integrate Redux Persist to React Redux Store
To integrate Redux Persist with a React Redux store, you will need to do the following:
- Install the redux-persist library by running
npm install --save redux-persist
oryarn add redux-persist
in your project. - Import the
persistStore
andcreateMigrate
functions from the redux-persist library in your store configuration file. - Use the
createMigrate
function to create a migration plan for your state. - Use the
persistStore
function to create a persistor object and pass it to your store and the migration plan. - Import the
PersistGate
component from the redux-persist library and wrap your root component with it. Pass the persistor object as a prop to thePersistGate
component. - Configure the
store
andpersistor
in theindex.js
file. - Finally, configure the
reducer
to handle thePERSIST
action and return to the previous state.
You can also use configureStore
from redux-persist
to store the config and reduce the boilerplate in index.js
.
Here’s an example of how your store configuration file might look like:
import { createStore } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import rootReducer from './reducers';
const persistConfig = {
key: 'root',
storage,
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
export const store = createStore(persistedReducer);
export const persistor = persistStore(store);
You can find more information about how to use Redux Persist on the official documentation https://redux-persist.js.org/docs/getting-started/