React Native persist app data

React Native persist app data

In every app, there must be some data which we have to keep during entire app lifespan, or some data need to keep for future use. Like user details, an authentication token to manage session of the user. sometimes we need to keep data of users last state, because once the user comes back to the app after some time so the user should be in the same state from where he did leave. so let's begin, by considering that redux is already set up and working fine so we need to some changes in existing file.
Note: Here persist is done based on reducer so, we can white list and black list multiple reducers, so we have to make provision for that before so we can separate state which needs to persist. then whitelist it.

First, install the redux-presist

npm install --save redux-presist

Then make changes in store.js

// Necessary imports 
import { persistStore,persistReducer} from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import reducers from 'your/reducer/path'

// Persistor Configuration to whitelist and blacklist any reducer
const persistConfig = {
  key: 'root',
  whitelist: ['auth']

const persistedReducer = persistCombineReducers(persistConfig,reducers);

export default () => {
    const store = createStore(persistedReducer,applyMiddleware(thunk));
    const persistor = persistStore(store);
    return { store, persistor };

Make some changes in root file App.js or index.js

import { PersistGate } from 'redux-persist/integration/react';
import configureStore from './app/store';
import { Provider } from 'react-redux';
//get store and presist store from configure store
const { store, persistor } = configureStore();
function Root() {
return (
<Provider store={store}>
 <PersistGate loading={null} persistor={persistor}>
   <App />
export default Root;

Here PersistGate, hold the app until loading it completely so, in loading props we can pass any loader component that will be displayed until loads.

Conclusion: By using redux persist we can save applications data to the device without any hassle, it takes care of presist storage, and make us free from overhead thinking of write time, and frequency and write event (when to persist)

Related Article