React Native — redux-toolkit, redux-persist & redux-logger setup

In a React Native app we usually need a way to manage the global state. While there are a number of solutions available out there, Redux seems to be the most popular choice among developers right now.
In this tutorial, we will:
1. Integrate redux for our global state management, we will use redux-toolkit library which is intended to be the standard way to write Redux logic in a React app. It includes utility functions to simplify common redux use-cases like store setup, creating reducers & actions and immutable update logic.
2. We will also integrate redux-persist to persist the redux data in Async Storage.
3. We will add redux-logger middleware to log our redux actions & state.
Step 1. Let’s install all the dependencies
$ yarn add @reduxjs/toolkit react-redux redux-persist @react-native-async-storage/async-storage redux-logger
$ cd ios
$ pod install
Step 2. Create actions & reducers
- We will create two reducers: User and Counter.
- User reducer will contain a state isLoggedIn, this reducer will be persisted in AsyncStorage using redux-persist.
- Counter reducer will contain a state value, this reducer will not be persisted and it’s value will reset to initial state when app is closed.
- We will import UserReducer and CounterReducer in a file and pass it in
combineReducers()
to create the root reducer.
Step 3. Create store
- To persist any reducer, add it to whitelist array.
- We are adding logger middleware when app is running in debug mode.
- Redux-thunk middleware used for async actions is by default added in redux-toolkit.
4. Create selectors for User and Counter reducers
5. We will wrap our app with redux Provider
and PersistGate
6. We will create a wrapper component AppWrapper
- This AppWrapper component will conditionally render Login or Counter component based on
isLoggedIn
state.
useSelector
hook is used to retrieve state from the store. It accepts the selector function as parameter.useDispatch
hook is used to call actions.- We are calling
persistor.purge()
on logout. In reducer we return initial state onPURGE
action.
Final output —

Thanks for reading.
I hope you enjoyed this article and it helped you in some way.
More articles to come. Stay tuned.
You can find the code for this tutorial in this repo.
Also, find me on LinkedIn.