Question:
8 Steps to use Redux Persist in React Native

What is Redux Persist?

A library called Redux Persist is used to rehydrate and persist a Redux store. It enables the redux state to be loaded automatically upon restarting the application and stored in persistent storage. This helps ensure that even after the user closes the application, it remains in the same state. A range of storage systems, such as localStorage, AsyncStorage, and sessionStorage, are compatible with Redux Persist.


Why we use Redux Persist?

To store the Redux store's state in persistent storage, utilize Redux Persist. This feature allows the user to maintain their preferences and data even after closing the app or browser. Redux Persist further improves the user experience by enabling a prompt restoration of the application's state upon reopening.


When your app is launched, Redux usually sets its initial state. Rehydrating is the next action carried out by the Redux Persist team; they describe it as "fetching your persisted state and replacing any initial state."


The state of the application is managed and centralized by an open-source JavaScript library called >Redux. It maintains an application's entire state in a single, directly immutable state object. 


Redux Persist and React Native

AsyncStorage is a useful tool for local data storage when developing React Native applications.  AsyncStorage is an asynchronous key-value storage system that holds all of the application's data. Redux Persist retrieves this persisted state and saves it back to Redux when the React app is launched.


Redux usually sets the initial state of your application when it launches. Next, rehydration—also known as fetching your persisted state and replacing any initial state—is carried out by the Redux Persist team.


The state of the application is centrally managed and organized by the open-source JavaScript library Redux. It is referred to as a "immutable state object" because it stores all of the state information for an application in a single, unchangeable object. 


Step 1: Install redux-persist:


To use Redux Persist in React Native first we have to install the redux-persist


npm install redux


Developers can save the Redux store in persistent storage, like the local storage, with the Redux Persist library. Therefore, even after refreshing the browser, the site state will still be preserved.


Step 2: Setup Redux Persist:

Make a store.js file in the project directory. The setup and configuration for Redux Persist will be included in this file.


Import the persistStore, createStore, and persistReducer functions from redux-persist into the store.js file:


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

import React from 'react';

import { StyleSheet, Text, View } from 'react-native';


export default function BooksListApp() {

  return (

    <View style={styles.container}>

        <Text style={styles.paragraph}>React Native ToDo App with Redux Persist Text>

          <Text style={styles.title}> Add ToDo HereText>

          <TextInput

            style={styles.input}

            mode="outlined"

            label="Task"

            value={task}

             onChangeText={task => setTask(task)}

          />

          <Button title='Add' color="#841584"  />

      <FlatList

        data={todos}

        keyExtractor={(item) => item.id}

        renderItem={({item, index}) => {

          return (

              <Text style={styles.list}>{item.task}Text>

          );

        }}

      />

    View>

  );

}


const styles = StyleSheet.create({

  container: {

    flex: 1,

    paddingTop: Constants.statusBarHeight,

    backgroundColor: '#ecf0f1',

    padding: 10,

  },

  paragraph: {

    margin: 24,

    fontSize: 18,

    fontWeight: 'bold',

    textAlign: 'center',

  },

  title: {

    margin: 10,

    fontSize: 16,

    fontWeight: 'bold',

    textAlign: 'center',

  },

  list: {

    fontSize: 18,

    fontWeight: 'bold',

    textAlign: 'center',

  },

  input: {

    height: 40,

    margin: 12,

    borderWidth: 1,

    padding: 10,

  },

});


Step 3: Set up Redux

Install redux by endearing the below command


npm install redux


Step 4: Create action creators

Redux manages application state with one JavaScript object. We can dispatch actions to change an object.


Let's create a redux state management folder. In it, create action.js to set up action types and creators.


export const ADD_TODO = "ADD_TODO";


let todoId = 0;


export const addTodo = task => ({

  type: ADD_TODO,

  payload: {

    id: ++todoId,

    task

  }

});


It is obvious what the action type ADD_TODO entails. When we need to add a new task to update the state, we call it.


Step 5: Creating the reducer

A reducer updates the state by making the required modifications to the object that represents the state after an action has been sent out. The reducer is a pure function that must return the default state in exchange for two arguments: the action being performed and the current state.


Now that we have a new file in the redux folder, let's import the action type that we created previously. Additionally, we'll establish the initial app state, which will include the following:


import { ADD_TODO } from "./action";


const initialState = {

  todos: []

};


const todoReducer = (state = initialState, action) => {

  switch (action.type) {

    case ADD_TODO: {

      const { id, task } = action.payload

      return {

        ...state,

        todos: [ ...state.todos, { id, task }]

      };

    }

    default:

      return state;

  }

}


export default todoReducer;


The reducer function that we called todoReducer is defined in the line of code that you just looked at. InitialState is the first argument and action is the second argument of this function.


Step 6: Configure the Redux store

The Redux store manages the application state and makes it accessible to all components. Reducers and actions are combined into one cohesive unit, known as the Redux store.


Redux provides a createStore method that we will use to configure a Redux store. The argument it anticipates is the reducer itself. 


Create a store.js file inside the redux folder, and then initialize the Redux store as follows:


import { createStore } from "redux";

import todoReducer from './reducers';


export default createStore(todoReducer);


The next step is to pass the Redux store to an asynchronous higher-order component called Provider, which will then make the store available throughout the entire app.


Use React Redux's Provider to encapsulate your app in the App.js file:


import store from './redux/store';

import { Provider } from 'react-redux';


const App = () => {

  return (

    {store}>

      

    

  );

}


export default App;


In the code that you can find above, we have established a connection between the Redux store and the state as well as the React components. Consequently, the state of this application can be accessed at any time by any component within this application.


Step 7: Action dispatching

Let's write a function using Redux set up, that executes when a user adds a to-do. Add the code below in Todo.js:

import { useSelector, useDispatch } from 'react-redux';

import { addTodo } from './redux/action';


const [task, setTask] = React.useState('');

  const  todoList  = useSelector(state => state.todos);

  const dispatch = useDispatch();



  const handleAddTodo = () => {

    dispatch(addTodo(task))

    setTask('')

  }

We imported the useSelector hook from React Redux for getting the state in this component and useDispatch for dispatching an action. We then call the function when the Add button is clicked:


<Button title='Add' color="#841584" onPress={handleAddTodo} />


The addTodo action creator is now run when we add an item to the input field and click the button, which then sends the ADD_TODO action to the reducer so that the item is added and the app's state is updated.


You'll see that the reducer is operating at this point, and our to-do app is also operational. However, you'll see that all the things we added are gone when we temporarily leave the application and then reopen it, showing that the Redux state has been restored to its initial state.


Using Redux Persist, we can preserve the items we've added. So, even if we close the app and open it again, our tasks are still there.


Step 8: Integrate Redux persist

Let's use the following command to install the Redux Persist package and the React Native AsyncStorage package:


npm i redux-persist @react-native-async-storage/async-storage



We’ll use persistStore, and persistReducer from Redux Persist and add the below-mentioned configuration:


import AsyncStorage from '@react-native-async-storage/async-storage';

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

import storage from 'redux-persist/lib/storage' 


const persistConfig = {

  key: 'root',

  storage: AsyncStorage,

}


You must pass both the key and the storage engine to set up React Persist. Both of these are mandatory. Other configurations such as whitelist, blacklist, version, stateReconciler, and debug are available as optional extras. You have the option of including something in the blacklist if you do not want it to persist as part of your state. You also have the option of using the whitelist to define the aspects of the state that you want to remain. 


At this point, we will invoke the persistReducer, providing it with the config object as well as our todoReducer.


In addition to this, we export the persistor, which is an object that is wrapped around the original store and is returned by the persistStore method.


const persistedReducer = persistReducer(persistConfig, todoReducer)


export const store = createStore(persistedReducer)

export const persistor = persistStore(store)



When the configuration is complete, the code in our store.js file will look like the following:


import AsyncStorage from '@react-native-async-storage/async-storage';

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


import todoReducer from './reducers';

import { createStore } from 'redux'

import storage from 'redux-persist/lib/storage' 


const persistConfig = {

  key: 'root',

  storage: AsyncStorage,

}


const persistedReducer = persistReducer(persistConfig, todoReducer)


export const store = createStore(persistedReducer)

export const persistor = persistStore(store)



Now we have to update App.js by importing PersistGate and wrap the app in it:

import * as React from 'react';

import { Text } from 'react-native';

import { PersistGate } from 'redux-persist/integration/react'

import MyTodo from './Todo';



import {store, persistor} from './redux/store';

import { Provider } from 'react-redux';


const App = () => {

  return (

    {store}>

    {Loading...} persistor={persistor}>

      

    

    

  );

}


export default App;


Redux Persist keeps the Redux store in AsyncStorage for us. Even if the app is closed and reopened at a later time, AsyncStorage will still get the data from the asynchronous storage and use it to initialize the Redux store.


Final thoughts:

In the end, Redux Persist is a powerful tool for keeping track of the state of React Native apps. It lets us store and get state from local storage so that our application can be used even after a restart or a page refresh. It is easy to set up, and it integrates with other libraries, such as Redux Thunk and React Navigation. By following the steps above, it's easy to set up Redux Persist and use it in your React Native apps.


Suggested blogs:

>Why component isn’t rendering each time form is submitted in React

>Why Ternary operator logic not working for boolean

>How to delete documents from a mongoDB collection without an error?

>I am not able to get the Header and Footer of the React table in the UI

>What is React Native useState update

>Will getServerSideProps be populated when cached value from an API call?

>Not using useEffect dependencies causing state to not change


Adequate Infosoft

Adequate Infosoft

Submit
0 Answers