Building Powerful Apps: Integrating Redux Toolkit in React Native

In this blog, we will learn about redux toolkit integration in react native.
Before starting actual integration first, we will see what redux is, then we deep dive into redux toolkit definitions and then the installation guide, one practical demo example with running code. If you follow the full blog step by step then you will get a clear idea about store configuration, writing reducer functions & dispatching redux actions & fetch redux state from the redux store.

What is Redux?

Redux is a simple store to store the state of the variable in our application. Redux is an open-source JavaScript library. Redux is mainly used for state management. It is commonly used in libraries like React and Angular for building user interfaces. Redux helps you to write applications that behave consistently, run in different environments, and are easy to test.

Redux can be described in three main fundamental principles:

  1. Single source of truth: The global state of your application is stored in an object tree within a single store.
  2. The state is read-only: The only way to change the state is to emit an action, an object describing what happened.
  3. Changes are made with pure functions only.

What is Redux Toolkit?

Redux toolkit is a toolset for efficient redux development and now the official redux community also strongly recommends the use of the redux toolkit.
It includes several utility functions that simplify most common redux use cases like store setup, immutable update logic, and creating an entire slice of state at once without writing any action creator or action types by hand. It also includes the most commonly used addons like redux-thunk for writing async logic and reselects for writing selector functions.

So you don’t need to add redux thanks separately as middleware or if you want to add different middleware of your choice redux toolkit gives you the feasibility to do that.

Why Should We Use Redux Toolkit?

The redux toolkit makes it easy to write good redux applications and speed up development. It is a recommended best practice, providing good default behaviours, catching mistakes, and allowing you to write simpler code.

The redux toolkit is beneficial for all redux users regardless of skill level and experience.

Note that you are not required to use the redux toolkit to use redux. There are many existing applications that use other redux wrapper libraries, or write all redux logic “by hand”, and if you still prefer to use a different approach, go ahead!

Now we just covered the theoretical part like what is a redux toolkit, why should we use it?
In the next step, we will see installations and practical demos from the scratch

Related read: How To Implement Redux Toolkit With React Js?

Installation

Redux Toolkit

Redux toolkit includes the Redux core as well as other key packages like Thunk & Reselect

🔸 Step 1

# NPM

npm install @reduxjs/toolkit react-redux

# Yarn

yarn add @reduxjs/toolkit react-redux

Redux Core

To install the stable version:

🔸 Step 2

# NPM

npm install redux

# Yarn

yarn add redux

That’s it from the installation side you just need to add these two packages and you don’t require to do any modifications and changes on the Android and Ios. If you don’t want to add these packages manually then you can create react app with the redux template.

Start new apps with react and redux by using the official Redux+JS template or Redux+TS template for creating react app, which takes advantage of the redux toolkit and react redux’s integration with react components.

Using the below command you setup your app with the redux template:

# Redux + Plain JS template
npx create-react-app my-app –template redux

# Redux + TypeScript template
npx create-react-app my-app –template redux-typescript

Hire Our Experienced Full Stack React.js Developers to Meet Your Business Requirements.

Now we are going to see one practical example, in this example, you will learn store configuration & writing reducers, how to dispatch actions and display the redux state on the front side.

🔸 Step 1: Create A Redux Store

Create a file named src/redux/app/store.js. Import the configureStore API from the redux toolkit. We’ll start by creating an empty redux store, and exporting it:

//src/redux/app/store.js.
import { configureStore } from '@reduxjs/toolkit'


const store = configureStore({
reducer:{},
  })
 
  export default store;

This creates a redux store, and also automatically configures the redux devtools extension so that you can inspect the store while developing.

  • configureStore: sets up a well-configured redux store with a single function call, including combining reducers, adding the thunk middleware, and setting up the Redux DevTools integration. configureStore accepts a reducer function as a named argument

🔸 Step 2: Provide The Redux Store to React

Once the store is created, we can make it available to our react components by putting a react-redux <Provider> around our application in App.js. Import the redux store we just created, put an <Provider> around your <App>, and pass the store as a prop.

//App.js


import React from 'react';
import { Provider } from 'react-redux'
import store from './src/redux/app/store'
import AppContainer from './src/containers/AppContainer';


function App() {
  return (
<Provider store={store}>
  <AppContainer/>
</Provider>
  );
}

export default App:

  • Provider: The <Provider> component makes the redux store available to any nested components that need to access the redux store.

🔸 Step 3: Create A Redux State Slice

Add a new file named src/redux/reducer/counter/counterSlice.js.n that file, and import the createSlice API from the redux toolkit.

Creating a slice requires a string name to identify the slice so in the below example we give the name as ‘counter’.
Also, it requires an initial state value so in the below example we added the initial state variable ‘value’ and the initial value is 0.
It also requires reducer functions to define how the state can be updated. In the below code example we added two reducer functions, the first one is ‘increment’ to increment the initial state value and the second one is ‘decrement’ to decrement the state value.

At last, we exported the generated redux action creators and the reducer function for the whole slice.

//counterSlice.js
import { createSlice } from '@reduxjs/toolkit';
export const counterSlice = createSlice({
name: 'counter',
initialState: {
count: 0,
},
reducers: {
increment: state => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
state.count += 1;
},
decrement: state => {
state.count -= 1;
},
},
});
// Action creators are generated for each case reducer function
export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;
  • createSlice:- a function that accepts the initial state, object of reducer functions and slice name and it will automatically generate action type and action creator that correspond to the reducers and state.

🔸 Step 4: Add Slice Reducers to the Store

Next, we need to import the reducer function from the counter slice and add it to our store. By defining a field inside the reducer parameter, we tell the store to use this slice reducer function to handle all updates to that state.

//final store.js file
//store.js
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from '../reducer/counter/counterSlice';


const store = configureStore({
reducer:{
    counter: counterReducer
}
  })
 
  export default store;

🔸 Step 5: Use Redux State and Actions in Components

Now we can use the react-redux hooks to let react native components interact with the redux store. We can read data from the store with useSelector, and dispatch actions using useDispatch.

  • useSelector:- The equivalent of map state to props is useSelector. It takes in a function argument that returns the part of the state that you want. In our case, we have the following keys from the state defined: value. We defined these earlier when creating slices.
  • useDispatch:- The equivalent of map dispatch to props is useDispatch. We will invoke useDispatch and store it to a variable, dispatch. In our case, use effect calls a dispatch with the following action: dispatch(increment()) or dispatch(decrement())

Create a src/screens/counter/Counter.js file, then import the counter component into App.js and render it as <Counter/>.

//Counter.js
import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import { decrement, increment } from '../../redux/reducer/counter/counterSlice';

function Counter() {
const { count } = useSelector(state => state.counter);
const dispatch = useDispatch();

// using this function we will dispatch increment reducer function
const onIncrementButtonPress = () => {
dispatch(increment());
};

// using this function we will dispatch decrement reducer function
const onDecrementButtonPress = () => {
dispatch(decrement());
};

return (
<View style={styles.mainContainer}>
<Text style={styles.textStyle}>{count}</Text>
<View style={styles.btnContainer}>
<TouchableOpacity onPress={() => onIncrementButtonPress()} style={styles.btnStyle}>
<Text style={styles.btnTextStyle}>{'+'}</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => onDecrementButtonPress()} style={styles.btnStyle}>
<Text style={styles.btnTextStyle}>{'-'}</Text>
</TouchableOpacity>
</View>
</View>
);
}

export default Counter;
const styles = StyleSheet.create({
mainContainer: {
flex: 1,
marginTop: 50,
},
btnContainer: {
flexDirection: 'row',
justifyContent: 'space-around',
},

btnStyle: {
height: 40,
width: 60,
alignItems: 'center',
backgroundColor: 'gray',
borderRadius: 6,
justifyContent: 'center',
},
btnTextStyle: { color: 'white', fontWeight: '700' },
textStyle: { textAlign: 'center', fontWeight: '700' },
});

In the above example, we are fetching the redux state using the useSelector hook provided by react-redux and dispatching action using the useDispatch hook.

Now, any time you click the “+” and “-” buttons:

  • The corresponding Redux action will be dispatched to the store.
  • The counter slice reducer will see the actions and update its state.
  • The <Counter> component will see the new state value from the store and re-render itself with the new data.
coma

Conclusion

In this blog, we explored the integration of the Redux Toolkit in React Native applications. We started by understanding the basics of Redux and its principles, followed by an introduction to Redux Toolkit and its benefits. We then went through the installation process for Redux Toolkit and its core packages.

Next, we delved into the practical implementation of the Redux Toolkit in a React Native app. We covered topics such as creating a Redux store, providing the store to React components using the <Provider> component, creating a Redux state slice using createSlice, and adding slice reducers to the store.

Finally, we demonstrated how to use Redux state and actions in React Native components by utilizing the useSelector and useDispatch hooks provided by React Redux. We showcased an example of a counter component that interacts with the Redux store to display and update the counter value.

Nandkishor S

Software Engineer

Nandkishor Shinde is a React Native Developer with 5+ years of experience. With a primary focus on emerging technologies like React Native and React.js. His expertise spans across the domains of Blockchain and e-commerce, where he has actively contributed and gained valuable insights. His passion for learning is evident as he always remains open to acquiring new knowledge and skills.

Keep Reading

Keep Reading

Enhance Your Epic EHR Expertise in Just 60 Minutes!

Register Here
  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?