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.
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:
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.
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?
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
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
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.
🔸 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:
🔸 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;
🔸 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.
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:
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 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.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowEnhance Your Epic EHR Expertise in Just 60 Minutes!
Register HereMindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork