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:
- Setting up Redux in your React Native project
- Creating a Redux store
- Defining actions and reducers
- Connecting Redux to your React components
- 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.
- 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.
- Inside your project, create a new folder called
store
and a file calledstore.js
:
mkdir store
touch store/store.js
- 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.
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
- Inside the
store
folder, create another folder calledreducers
, and inside it, create a file calledcounterReducer.js
:
mkdir store/reducers
touch store/reducers/counterReducer.js
- 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.
- Inside the
reducers
folder, create a file calledindex.js
:
touch store/reducers/index.js
- 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.
- Open
App.js
and wrap your app in theProvider
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.
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.
- Create a new file called
Counter.js
in your project root:
touch Counter.js
- 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.
- Run your app:
npm start
- 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
anduseDispatch
to access state and dispatch actions from a component.
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!