Ciprian Craciun - FrontEnd Developer

Ciprian Craciun

FrontEnd/Web Developer

Engineering is about making a product better, learning from past mistakes and create a process which is easy for all to understand.

How to use redux persist with react native

Working with react or react-native and having state management like redux, we have cases when we need to persist our data on refresh, for this task we have redux persist witch is very useful.

So let’s start to add to our react native app, first, we need to install it with yarn or npm: yarn add redux-persist. In our store configuration from react-native we need persistReducer and persistStore

import { persistStore, persistReducer } from 'redux-persist';

The key of configuration is to create a config object with the key ‘root’ , in my case the config is looking like this:

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
  blacklist: ['user'],

As storage we use AsyncStorage because we work with react native and blacklist is set to user, meaning that I don’t want to keep the data from user reducer on refresh. Keep in mind that if you have a complex redux store you need to specify how many levels of the state you want to keep on refresh, so for this, you need to use state reconciler, read more on the official docs

After we’ve added a root configuration we need to use what we imported at the beginning:

const persistedReducer = persistReducer(persistConfig, reducer);

And our createStore function would become:

const store = createStore(persistedReducer, composeEnhancer(applyMiddleware(thunk, ...middleware)));
export const persistor = persistStore(store);

composeEnhancer is another discussion, in my case keeps configuration for web dev tools and redux-thunk.

Because we are using react native with redux, we need to include one more configuration in the App.js file, like redux using Provider component as a wrapper, for redux-persist we have PersistGate.

 redux persist  configuration
import { AppRegistry } from 'react-native';
import React from 'react';
import { PersistGate } from 'redux-persist/integration/react';
import { Provider } from 'react-redux';
import App from './app/App';
import store, { persistor } from './app/config/store';
import { name as appName } from './app.json';
const AppRedux = () => (
  <Provider store={store}>
    <PersistGate persistor={persistor} loading={null}>
      <App />
AppRegistry.registerComponent(appName, () => AppRedux);

As we can see Provider is the first wrapper then is PersistGate with persistor and loading. You can add ActivityIndicator if you are using react-native.

Sharing is caring!

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *