Advertisement
Scroll to top
Read Time: 9 min

Redux is a library for state management that ensures that the application logic is well-organized and that apps work as expected. Redux makes it easy to understand your application's code regarding when, where, why, and how the state of the application is updated.

Redux is made up of the following key parts:

  • actions
  • reducers
  • store
  • dispatch
  • selector

In this post, we'll look at each part of the Redux architecture in turn.

Actions and Action Creators

An action is a plain JavaScript object that has a type field and an optional payload. It can also be thought of as an event that describes something that has happened.

1
const addTaskAction = {
2
    type: 'task/taskAdded'
3
,payload: 'Laundry'
4
}

Action creators are just functions that create and return action objects.

1
const addTask = text => {
2
  return {
3
    type: 'task/taskAdded'',

4
    payload: text

5
  }

6
}

Reducers

reducer is also a function that receives the current state and an action object, updates the state if necessary, and returns the new state. A reducer is not allowed to modify the existing state; instead, it copies the existing state and changes the copied values. In other words, the reducer should be a pure function.

Here is an example. 

1
const initialState = { value: 0 }
2
3
function counterReducer(state = initialState, action) {
4
  // Check to see if the reducer cares about this action

5
  if (action.type === 'counter/increment') {
6
    // If so, make a copy of `state`

7
    return {
8
      ...state,
9
      // and update the copy with the new value

10
      value: state.value + 1
11
    }
12
  }
13
  // otherwise return the existing state unchanged

14
  return state
15
}

Store

A store is an object that stores the current state of a Redux application. You create the initial state of the store by passing a reducer to the configureStore functIon.

1
import { configureStore } from '@reduxjs/toolkit'
2
3
const store = configureStore({ reducer: counterReducer })
4
5
console.log(store.getState())

To get the current state of a store, use the getState() function as above.

Dispatch and Selectors

dispatch() is a Redux store method and is used to update the state by passing an action object. Here, we create a task/taskAdded action with the addTask() action creator, and then pass it to the dispatch() method.

1
store.dispatch(addTask('pick up laundry'))

Selectors are used for reading data from a store.

Tutorial on Using Redux With React Native

In this React Native Redux tutorial, you will develop an app that allows a user to choose from a given set of subjects. The app will contain two screens, and you will also learn how to navigate between them using react-navigation

Create a New React App

Create a new project using the Expo CLI tool.

1
expo init ReduxApp

Currently, you have a single component, App.js displaying a welcome message. 

Create two new components in Home.js and Subjects.js. The home component will be the first screen a user sees, and the subjects component will display all the subjects in our app. Copy the code from App.js and add it to Home.js and Subjects.js.

Modify Home.js and Subjects.js to use Home and Subjects instead of the App class.

1
//Home.js 
2
3
import React from 'react';
4
import { StyleSheet, Text, View } from 'react-native';
5
6
class Home extends React.Component {
7
  render() {
8
    //...
9
  }
10
}
11
12
// ...
13
export default Home;

Subects.js should look similar.

Navigating Between Screens

Currently, there is no way to navigate between the two screens. The stack navigator allows your app to transition between screens where each new screen is placed on top of a stack.

First, install @react-navigation/native and its dependencies.

1
npm install @react-navigation/native

For an Expo-managed project, install the following.

1
expo install react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-community/masked-view

Go to App.js and import react-native-gesture-handler at the top. You also need to add NavigationContainer and createStackNavigator to App.js. Then, to add navigation capabilities, wrap the components inside the App class in a NavigationContainer component. 

1
import { NavigationContainer } from '@react-navigation/native';
2
import { createStackNavigator } from '@react-navigation/stack';
3
4
const Stack = createStackNavigator();
5
6
// ...

7
8
class App extends React.Component {
9
  render() {
10
    return (
11
      <NavigationContainer>
12
        <Stack.Navigator>
13
          <Stack.Screen
14
            name="Home"
15
            component={Home}
16
          />

17
          <Stack.Screen
18
            name="Subjects"
19
            component={Subjects}
20
          />

21
        </Stack.Navigator>

22
      </NavigationContainer>

23
    );
24
  }
25
}
26
27
// ...

Now the navigator is aware of your screens, and you can provide links for transitioning between screens.

Redux in a React Native App

As we mentioned earlier, Redux is a state management tool, and you will use it to manage all the states of the application. Our application is a subject selector where the user chooses the subjects from a predefined list.

First, install the Redux packages.

1
npm install redux react-redux

A Redux app follows the following conditions:

  • The state completely describes the condition of the app at any point in time.
  • The UI is rendered based on the state of the app. 

For example, when a user clicks a button, the state is updated, and the UI renders the change based on the state.

Create a Reducer

The reducer will be responsible for keeping the state of the subjects at every point in time.

Create the file SubjectsReducer.js at the root level and add the following code.

1
import { combineReducers } from 'redux';
2
3
const INITIAL_STATE = {
4
  current: [],
5
  all_subjects: [
6
    'Literature',
7
    'Speech',
8
    'Writing',
9
    'Algebra',
10
    'Geometry',
11
    'Statistics',
12
    'Chemisrty',
13
    'Biology',
14
    'Physics',
15
    'Economics',
16
    'Geography',
17
    'History',
18
  ],
19
};
20
21
const subjectsReducer = (state = INITIAL_STATE, action) => {
22
  switch (action.type) {
23
    default:
24
      return state
25
  }
26
};
27
28
export default combineReducers({
29
  subjects: subjectsReducer
30
});

In this file, you create an INITIAL_STATE variable with all the curriculum subjects and export the subjects reducer as a property called subjects. So far, the subjects reducer doesn't respond to any actions—the state can't change.

Create an Action

An action has a type and an optional payload. In this case, the type will be SELECT_SUBJECT, and the payload will be the array index of the subjects to be selected.

Create the SubjectsActions.js file at the root level and add the following code.

1
export const addSubject = subjectsIndex => (
2
  {
3
    type: 'SELECT_SUBJECT',
4
    payload: subjectsIndex,
5
  }
6
);

Now, we'll update the reducer to respond to this action.

1
// ...

2
3
const subjectsReducer = (state = INITIAL_STATE, action) => {
4
  switch (action.type) {
5
    case 'SELECT_SUBJECT':
6
     
7
      // copy the state 

8
      const { current,  all_subjects,} = state;
9
10
      //remove a subject from the all_subjects array

11
      
12
      const addedSubject = all_subjects.splice(action.payload, 1);
13
14
      // put subject in current array

15
      current.push(addedSubject);
16
17
      // update the redux state to reflect the change

18
      const newState = { current, all_subjects };
19
      
20
      //return new state

21
      return newState;
22
23
    default:
24
      return state
25
  }
26
};
27
28
// ...

Add the Reducer to the App

Now, open App.js and create a new store for the app using the createStore() function. We also make that store available to the components in our app by wrapping them in the <Provider> component. This will ensure that the store's state can be accessed by all of the child components.

1
import 'react-native-gesture-handler';
2
import React from 'react';
3
import { Provider } from 'react-redux';
4
import { createStore } from 'redux';
5
import { StyleSheet } from 'react-native';
6
import { NavigationContainer } from '@react-navigation/native';
7
import { createStackNavigator } from '@react-navigation/stack';
8
import subjectsReducer from './SubjectsReducer';
9
import Home from './Home';
10
import Subjects from './Subjects';
11
12
// ... . rest of the code

13
14
const store = createStore(subjectsReducer);
15
16
class App extends React.Component {
17
  // ...

18
19
  render() {
20
    return (
21
      <Provider store={store}>
22
        <NavigationContainer>
23
          //.. rest of the code

24
        </NavigationContainer>

25
      </Provider>

26
    )
27
  }
28
}

Add Redux to the Components

Now let's see how to make state data available to components with the connect() function. To use connect(), we need to create a mapStateToProps function, which will map the state from the store to the props in the two components.

Open Home.js, map the state, and render the values for the current subjects (which will be found in this.props.subjects.current). Also, add a button to navigate to the Subjects component.

1
import React from 'react';
2
import { connect } from 'react-redux';
3
import { StyleSheet, Text, View, Button } from 'react-native';
4
5
class Home extends React.Component {
6
  render() {
7
    return (
8
      <View style={styles.container}>
9
        <Text>You have { this.props.all_subjects.current.length } subjects.</Text>

10
        <Button
11
          title="Select more subjects"
12
          onPress={() =>
13
            this.props.navigation.navigate('Subjects')
14
          }
15
        />

16
      </View>

17
    );
18
  }
19
}
20
21
22
const mapStateToProps = (state) => {
23
  const { subjects } = state
24
  return { subjects }
25
};
26
27
export default connect(mapStateToProps)(Home);

Similarly, we'll use connect in the Subjects.js file to map the state to the component properties. 

1
import React from 'react';
2
import { connect } from 'react-redux';
3
import { StyleSheet, Text, View, Button } from 'react-native';
4
5
class Subjects extends React.Component {
6
  render() {
7
    return (
8
      <View style={styles.container}>
9
        <Text>My Subjects!</Text>

10
        />
11
      </View>

12
    );
13
  }
14
}
15
16
//...

17
18
const mapStateToProps = (state) => {
19
  const { subjects } = state
20
  return { subjects }
21
};
22
23
export default connect(mapStateToProps)(Subjects);

We'll also add the code to display all the subjects in the Subjects component and a button to navigate to the Home screen. You will also add a button that will add the addSubject action to Subject.js. Here's what the final render() method in Subject.js should look like:

1
class Subject extends React.Component {
2
  render() {
3
    return (
4
      <View style={styles.container}>
5
        <Text>Select Subjects Below!</Text>

6
7
        {
8
          this.props.subjects.all_subjects.map((subject, index) => (
9
            <Button
10
              key={ subject }
11
              title={ `Add ${ subject }` }
12
              onPress={() =>
13
                this.props.addSubject(index)
14
              }
15
            />

16
          ))
17
        }
18
19
        <Button
20
          title="Back to home"
21
          onPress={() =>
22
            this.props.navigation.navigate('Home')
23
          }
24
        />

25
      </View>

26
    );
27
  }
28
}

The final app should look like this.

redux appredux appredux app

Conclusion

Redux is a valuable tool, but it's only useful when used in the right way. Some of the situations where Redux might be helpful include code that is being worked on by many people or applications that contain large amounts of application state.

In this tutorial, you learned how to set up a React Native app using Redux.

The Best React Native App Templates on CodeCanyon

CodeCanyon is a digital marketplace that offers the best collection of React Native themes and templates. With a React Native app template, you can get started building your apps in the fastest time possible.

React Native app templatesReact Native app templatesReact Native app templates

If you have trouble deciding which React Native template on CodeCanyon is right for you, this article should help: 


Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.