React Native + Redux Tool kit + AsyncStorage
Tags: react, reactnative, javascript, tutorial
Published: 2023-05-17 11:31:27

3 steps to add redux with a redux toolkit and async storage in a react-native application

## Under the Hood
The story begins when I am developing a non-custodial wallet app and web3 mobile app using react-native.

Once the user creates an account or wallet he/she can view all the wallets and addresses and check the balance.

After creating an account I want to store wallets and async storage as we will not be saving wallets in the database.

## Tech Stack
And since I am using react-native so redux will be the state management.

But redux now provides the latest or upgrade way to write actions and reducers called slice, so I’ll be using slice.

- React
- React Native
- Redux Toolkit
- Redux Persist
- AsyncStorage
Redux persists helps to persist the reducer states and for that, it uses async storage in react-native just like local storage in react.

## Installing Packages
- react
- react-native
- react-redux
- redux-persists
- @react-native-async-storage/async-storage

## Creating Reducer
The Redux toolkit now provides an easy way to write reducers and actions in the same method.

Below is the code

```
import {createSlice} from '@reduxjs/toolkit';

const initialState = {
  wallet: [
    {
      walletAddress: 'zxcvbnm',
      balance: 100,
    },
    {
      walletAddress: 'asdfghjkl',
      balance: 300,
    },
    {
      walletAddress: 'qwertyuiop',
      balance: 400,
    },
  ],
  activeWallet: null,
};
const walletSlice = createSlice({
  name: 'userWallet',
  initialState,
  reducers: {
    addWallet: (state, action) => {
      return {...state, wallet: action.payload};
    },
    addActiveWallet: (state, action) => {
      return {...state, activeWallet: action.payload};
    },
  },
});
export const {addWallet, addActiveWallet} = walletSlice.actions;
export const reducer = walletSlice.reducer;
```

- First, we import createSlice
- Define initial states
- Create a slice that contains name, initialState and reducers as the key
- Define reducers
- Export actions and reducer from the slice method
In just 5 steps, we have to define reducer and action altogether now need to create 2 separate files for actions and reducers and define constants to connect them.

## Creating Store
This might seem a little tricky but it’s also not that hard.

- Import the required methods such as storage, reducer stores and persisted methods
- Define persistent configuration
- Define reducers or combine reducers if have multiple
- Create persisted reducers using persist reducer
- Create configure store by passing the root reducer
- Export store and persistor default at the end

```
import {configureStore, combineReducers} from '@reduxjs/toolkit';
import {persistReducer, persistStore} from 'redux-persist';
import {reducer} from './slice';
import AsyncStorage from '@react-native-async-storage/async-storage';

const persistConfig = {
  storage: AsyncStorage,
  key: 'root',
};
const rootReducer = combineReducers({
  reducer,
});

export const persistedReducer = persistReducer(persistConfig, rootReducer);
export const store = configureStore({
  reducer: persistedReducer,
});
export const persistor = persistStore(store);
```
Again in 6 steps, our store and persistor are created.

Why we need them, the store contains the entire app storage or data and the persistor basically tells the app how and where to persist the data.


## Wrapping Redux to Root App
The last step is to wrap redux to the root of the application along with persistor and store.

-  Wrap the ReduxPersistGate component to the root of the app components
- Wrap ReduxProvider to the ReduxPersistGate
- Pass persistor 
and store both PersistGate and ReduxProvider HOC respectively.

```
<ReduxProvider store={store}>
    <PersistGate persistor={persistor} loading={null}>
      <NavigationContainer>
        <Stack.Navigator initialRouteName="HomeScreen">
          <Stack.Screen
            name="HomeScreenTab"
            component={HomeScreenTab}
            options={{headerShown: false}}
          />
        </Stack.Navigator>
      </NavigationContainer>
    </PersistGate>
  </ReduxProvider>
```

Now in just 2 steps, our redux state management along with data storage async storage in our case is ready.

## Conclusion
Install the required packages

- Create a slice that basically gives actions and reducers
- Create a store, persisted store using the redux toolkit and async storage.
- Wrap Redux 
HOC to the root of the application
Hence in just 3 steps, we have redux-toolkit the latest redux package installed in our react-native app.

Keep developing
Shrey
[iHateReading](ihatereading.in)