In this tutorial, you’ll learn how to integrate Redux into your React Native app. Redux is a powerful state management tool that allows you to manage the state of your application in a predictable way, making it easier to scale and maintain. By the end of this tutorial, you’ll have a clear understanding of how to set up Redux, create actions, reducers, and share state across different screens.
What You Will Learn Today:
- Setting up Redux in a React Native app
- Creating a Redux store
- Creating actions and reducers
- Connecting components to the Redux store using
useSelector
anduseDispatch
- Sharing global state across different screens
Step 1: Installing Redux and React-Redux
First, we need to install the required libraries for Redux. Open your terminal and run the following command in your project directory:
npm install redux react-redux
This will install Redux and React-Redux, which are the core libraries needed to implement Redux in your app.
Step 2: Setting Up the Redux Store
Next, we’ll set up the Redux store. The store is where all the state of your app is managed.
- In your project’s root directory, create a folder called
redux
to hold your Redux logic. - Inside the
redux
folder, create a file namedstore.js
and add the following code:
import { createStore } from 'redux';
import rootReducer from './reducers';
// Create the Redux store
const store = createStore(rootReducer);
export default store;
- Now, create another folder called
reducers
inside theredux
folder. In this folder, create a file calledindex.js
, which will combine all your reducers (we’ll add more later as the app grows).
import { combineReducers } from 'redux';
import counterReducer from './counterReducer';
// Combine all reducers into one root reducer
const rootReducer = combineReducers({
counter: counterReducer,
});
export default rootReducer;
- Create a new file inside the
reducers
folder calledcounterReducer.js
. This will be our first reducer, which manages a simple counter state.
const initialState = {
count: 0,
};
const counterReducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
case 'DECREMENT':
return { ...state, count: state.count - 1 };
default:
return state;
}
};
export default counterReducer;
Explanation:
createStore
: This function creates the Redux store.combineReducers
: This is used to combine multiple reducers into a single root reducer.counterReducer
: This reducer manages the state of a simple counter with two actions: increment and decrement.
Step 3: Providing the Store to the App
Now that we have set up the store and a basic reducer, we need to provide the store to the entire app so that all components can access the global state.
- Open your
App.js
file and modify it as follows:
import React from 'react';
import { Provider } from 'react-redux';
import store from './redux/store';
import HomeScreen from './screens/HomeScreen';
export default function App() {
return (
<Provider store={store}>
<HomeScreen />
</Provider>
);
}
Explanation:
Provider
: TheProvider
component wraps the app and makes the Redux store available to all components within the app.- We import the store and pass it to the
Provider
.
Step 4: Dispatching Actions and Selecting State
Now that Redux is integrated, we’ll modify the HomeScreen to dispatch actions and select state from the store. We’ll add two buttons to increment and decrement the counter and display the current count from Redux.
Modify HomeScreen.js as follows:
import React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
export default function HomeScreen() {
const count = useSelector((state) => state.counter.count); // Get count from Redux
const dispatch = useDispatch(); // Dispatch actions
return (
<View style={styles.container}>
<Text style={styles.title}>Counter: {count}</Text>
<Button
title="Increment"
onPress={() => dispatch({ type: 'INCREMENT' })}
/>
<Button
title="Decrement"
onPress={() => dispatch({ type: 'DECREMENT' })}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
backgroundColor: '#f5f5f5',
},
title: {
fontSize: 24,
marginBottom: 20,
},
});
Explanation:
useSelector
: This hook allows us to access the Redux state. We use it to retrieve the current value of thecount
from thecounterReducer
.useDispatch
: This hook gives us access to thedispatch
function, which we use to send actions to the Redux store. Here, we dispatchINCREMENT
andDECREMENT
actions to update the state.
Step 5: Sharing State Between Screens
Redux is most powerful when you need to share state between multiple components or screens. Let’s extend this by passing the count
from the HomeScreen to the DetailsScreen.
- First, modify the HomeScreen.js to navigate to the DetailsScreen and pass the
count
:
<Button
title="Go to Details"
onPress={() => navigation.navigate('Details', { count })}
style={styles.button}
/>
- Next, modify DetailsScreen.js to display the count passed from the HomeScreen:
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function DetailsScreen({ route }) {
const { count } = route.params; // Get the count from route params
return (
<View style={styles.container}>
<Text style={styles.title}>Count from Redux: {count}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
backgroundColor: '#f5f5f5',
},
title: {
fontSize: 24,
marginBottom: 20,
},
});
Now, the DetailsScreen will receive the current value of the counter as a parameter and display it. This demonstrates how you can share global state across multiple screens using Redux.
Step 6: Recap and Summary
Today, you learned how to integrate Redux into your React Native app and manage global state. Here’s a quick summary of what you’ve done:
- Installed Redux and set up the Redux store.
- Created a simple reducer to manage the state of a counter.
- Used
useSelector
to access state anduseDispatch
to dispatch actions. - Shared state between the HomeScreen and DetailsScreen using Redux and navigation parameters.
With Redux in place, you can now manage state more effectively across multiple components and screens, which is essential for building more complex and scalable applications.
Next Up: Day 8 – Storing Data Locally Using AsyncStorage
In Day 8, we’ll focus on storing data locally using AsyncStorage. You’ll learn how to persist data, such as user preferences or app settings, across sessions, even when the app is closed and reopened.
Stay tuned for more exciting functionality tomorrow!