Day 2: Managing State with Redux in React Native


In this tutorial, you’ll learn how to integrate Redux into your React Native app to manage the global state. By the end of this lesson, you’ll be able to create actions, reducers, and a global state that can be shared across multiple components.


What You Will Learn Today:

  1. Setting up Redux in your React Native project
  2. Creating a Redux store
  3. Defining actions and reducers
  4. Connecting Redux to your React components
  5. Dispatching actions and updating state

Step 1: Installing Redux and React-Redux

To begin using Redux in your React Native app, you’ll need to install redux and react-redux. The redux package provides the core functionality of Redux, while react-redux connects Redux to React components.

  1. Install Redux and React-Redux:
npm install redux react-redux

Explanation:

  • redux: The core Redux library, which provides state management features like actions, reducers, and the store.
  • react-redux: A library that integrates Redux with React, allowing React components to access and update the Redux store.

Step 2: Setting Up the Redux Store

The Redux store is the central place where your app’s state is stored. Let’s create a store and configure it to work with your app.

  1. Inside your project, create a new folder called store and a file called store.js:
mkdir store
touch store/store.js
  1. Open store/store.js and set up the Redux store:
import { createStore } from 'redux';
import rootReducer from './reducers';

const store = createStore(rootReducer);

export default store;

Explanation:

  • createStore(): Creates a Redux store that holds the entire state of your app.
  • rootReducer: A placeholder for your combined reducers. We’ll define this next.
See also  Day 8: Progressive Enhancement – Making the App Usable in Low-Data Scenarios

Step 3: Defining Actions and Reducers

Redux actions represent events that can modify the state, while reducers define how the state changes in response to actions.

Creating a Reducer

  1. Inside the store folder, create another folder called reducers, and inside it, create a file called counterReducer.js:
mkdir store/reducers
touch store/reducers/counterReducer.js
  1. Open counterReducer.js and define the counter reducer:
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:

  • initialState: The initial state of the counter, with a default value of count: 0.
  • INCREMENT and DECREMENT: Action types that change the state of the counter.
  • switch-case: Checks the type of action and updates the state accordingly.

Creating a Root Reducer

Since Redux can have multiple reducers (one for each part of the state), we’ll combine them into a single root reducer.

  1. Inside the reducers folder, create a file called index.js:
touch store/reducers/index.js
  1. Open index.js and combine the reducers:
import { combineReducers } from 'redux';
import counterReducer from './counterReducer';

const rootReducer = combineReducers({
  counter: counterReducer,
});

export default rootReducer;

Explanation:

  • combineReducers(): Combines multiple reducers into a single root reducer. In this case, we have one reducer (counterReducer), but you can add more as your app grows.

Step 4: Connecting Redux to Your React Components

To access the Redux store from your React components, we need to connect the store to the app using the Provider component from react-redux.

  1. Open App.js and wrap your app in the Provider component:
import * as React from 'react';
import { Provider } from 'react-redux';
import store from './store/store';
import Counter from './Counter'; // A component that we will create to display and interact with the counter

export default function App() {
  return (
    <Provider store={store}>
      <Counter />
    </Provider>
  );
}

Explanation:

  • Provider: Wraps your app and makes the Redux store available to all components.
  • store: The Redux store we created in store.js is passed to the Provider, making it available throughout the app.
See also  Day 9: Implementing In-App Purchases in React Native

Step 5: Creating a Component to Dispatch Actions

Now let’s create a Counter component to display the current count and allow the user to increment or decrement it.

  1. Create a new file called Counter.js in your project root:
touch Counter.js
  1. Open Counter.js and add the following code:
import React from 'react';
import { View, Text, Button } from 'react-native';
import { useSelector, useDispatch } from 'react-redux';

export default function Counter() {
  const count = useSelector((state) => state.counter.count); // Access state from Redux store
  const dispatch = useDispatch(); // Dispatch actions to the store

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Count: {count}</Text>
      <Button title="Increment" onPress={() => dispatch({ type: 'INCREMENT' })} />
      <Button title="Decrement" onPress={() => dispatch({ type: 'DECREMENT' })} />
    </View>
  );
}

Explanation:

  • useSelector: A hook that allows you to access a specific part of the Redux state. In this case, we access state.counter.count.
  • useDispatch: A hook that allows you to dispatch actions to the Redux store. When a button is pressed, we dispatch either the INCREMENT or DECREMENT action.

Step 6: Testing Redux in Your App

Now that we’ve set up Redux and connected it to our React components, let’s run the app and test the functionality.

  1. Run your app:
npm start
  1. In your app, you should see the counter displayed along with two buttons (“Increment” and “Decrement”). Pressing the buttons should update the count in real-time.

Step 7: Recap and Summary

In today’s tutorial, you learned how to manage state globally using Redux in a React Native app. Here’s a quick summary of what you’ve done:

  • Installed Redux and React-Redux to manage global state in your app.
  • Set up a Redux store and combined reducers.
  • Created actions and reducers to manage the state.
  • Connected Redux to React components using the Provider component.
  • Used useSelector and useDispatch to access state and dispatch actions from a component.
See also  Day 3: Asynchronous State Management with Redux Thunk

With Redux in place, you can now manage complex state logic across multiple components in your app.


Next Up: Day 3 – Asynchronous State Management with Redux Thunk

In Day 3, we’ll extend Redux by adding Redux Thunk to handle asynchronous actions, such as making API requests and dispatching actions based on the results.

Stay tuned for more advanced features 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.