Pages

8 Steps to use Redux Persist in React Native

What is Redux Persist

Redux Persist is a library used to persist and rehydrate a redux store. It lets the redux state be saved to persistent storage and automatically loaded when the app is started again. This helps make sure that the application stays in the same state even after the user closes it. Redux Persist can be used with a variety of storage systems, including localStorage, AsyncStorage, and sessionStorage.


Why we use Redux Persist

Redux Persist is used to save the state of the Redux store in persistent storage. This lets the user keep their data and preferences even after closing the browser or app. Redux Persist also makes it possible for the application's state to be quickly restored when it is opened again, giving the user a better experience.


Redux typically establishes your app's basic state when it is launched. The Redux Persist team then performs rehydration, which they refer to as "fetching your persisted state and replacing any initial state."


An open-source JavaScript library called Redux is used to manage and centralize the application state. It keeps the state of a whole application in a single, directly unchangeable, immutable state object. Using actions and reducers, a new object is produced whenever something changes.


Redux Persist and React Native

When building a React Native app, you can use AsyncStorage to store your data locally.  AsyncStorage is a key-value storage system that stores all data for the whole app and works in an asynchronous way.


On launching the React app, Redux Persist retrieves this persisted state and saves it back to Redux.


Redux typically establishes your app's initial state when it launches. The Redux Persist team then performs rehydration, which they refer to as fetching your persisted state and replacing any initial state.


Redux, an open-source JavaScript library, is used to manage and centralize the application state. It keeps track of the state of an entire application in a single object that can't be changed directly and is called an "immutable state object." When something changes, a new object is created using actions and reducers.


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:

In your project directory, create a file called store.js. This file will contain the Redux Persist configuration and setup.


In the store.js file, import the persistStore, createStore, and persistReducer methods from redux-persist:


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 Here</Text>

          <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

  }

});


The action type ADD_TODO is self-explanatory. We call it when we need to update the state by adding a new todo.


Step 5: Creating the reducer

After an action has been sent out, a reducer will update the state by applying the necessary changes to the object that represents the state. The reducer is a pure function that accepts two arguments—the current state and the action being performed—and is required to return the default state.


Let's make a new file in the redux folder and import the action type that we made earlier in the process. We will also create an initial app state, which will consist of 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 line of code that you just looked at contains the definition of a reducer function that we referred to as todoReducer. This function's first argument is initialState, and its second argument is action.


Step 6: Setup Redux store

The application state is maintained by the Redux store, which allows any component to access it. The Redux store is an object that combines reducers and actions into a single cohesive unit.


To configure a Redux store, we will use the createStore method that is provided by Redux. The reducer itself is the argument that it expects. 


Inside the redux folder, make a store.js file, and then initialize the Redux store in the following manner:


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 (

    <Provider store={store}>

      <MyTodo/>

    </Provider>

  );

}


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, 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 in order 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 (

    <Provider store={store}>

    <PersistGate loading={<Text>Loading...</Text>} persistor={persistor}>

      <MyTodo/>

    </PersistGate>

    </Provider>

  );

}


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 in React Native apps. It lets us store and gets 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.

No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...