Day 7: Managing Global State with Redux


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:

  1. Setting up Redux in a React Native app
  2. Creating a Redux store
  3. Creating actions and reducers
  4. Connecting components to the Redux store using useSelector and useDispatch
  5. 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.

  1. In your project’s root directory, create a folder called redux to hold your Redux logic.
  2. Inside the redux folder, create a file named store.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;
  1. Now, create another folder called reducers inside the redux folder. In this folder, create a file called index.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;
  1. Create a new file inside the reducers folder called counterReducer.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.
See also  Versioning Your Database with Migration Bundles: A Comprehensive Guide

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.

  1. 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: The Provider 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 the count from the counterReducer.
  • useDispatch: This hook gives us access to the dispatch function, which we use to send actions to the Redux store. Here, we dispatch INCREMENT and DECREMENT actions to update the state.
See also  Amazon SES without domain verification, here are methods to send emails without direct domain access

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.

  1. 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}
/>
  1. 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 and useDispatch 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.

See also  Day 3: Adding Navigation Between Screens Using React Navigation

Stay tuned for more exciting functionality tomorrow!


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.