DEV Community

Cover image for Comprehensive guide to using Redux in React Native
codewithkaushik
codewithkaushik

Posted on

Comprehensive guide to using Redux in React Native

React Native Redux Example | How To Use Redux In React Native is today’s leading topic. Redux is a standalone state management library, which can be used with any library or framework. If your background is React developer, then you have used the Redux library with React.
Overview of React Native Redux Example

  • Step 1: Install React Native on mac.
  • Step 2: Add TextBox and Button.
  • Step 3: Define the state and input handler.
  • Step 4: Create actions, reducers, and components folder.
  • Step 5: Create a Reducer function.
  • Step 6: Create a Redux store.
  • Step 7: Pass the store to the React Native app.
  • Step 8: Connect React Native app to the Redux store.

Image description

React Native Redux Example Tutorial

The primary use of Redux is that we can use one application state as a global state and interact with the state from any react component is very easy, whether they are siblings or parent-child. Now, let us start the React Native Redux Example Tutorial by installing React Native on Mac first.

We start our project by installing React Native CLI globally on the Mac. You can skip the following command if you have already installed it.

#Step 1: Install React Native.
Type the following command.

npm install -g react-native-cli
Enter fullscreen mode Exit fullscreen mode

Okay, now for creating a new application, type the following command.

react-native@latest init AwesomeProject

Enter fullscreen mode Exit fullscreen mode

Now, after installing, we need to open this application in the two different Simulators.

For testing on iOS simulator, type the following command.

react-native run-ios
Enter fullscreen mode Exit fullscreen mode

If you have configured XCode correctly, then one iOS device will pop up as well as the development server will also start.

To open the project inside the Android Simulator, type the following command.

react-native run-android
Enter fullscreen mode Exit fullscreen mode

Install the @reduxjs/toolkit and react-redux library using the following command.

npm install @reduxjs/toolkit react-redux
  #or
yarn add @reduxjs/toolkit react-redux
Enter fullscreen mode Exit fullscreen mode

#Step 2: Add Button into the App.js.
Okay, so we will add a text box and button to add places. So let us add the View and Button. Also, we will add the flexbox layout. Write the following code inside the **App.js **file.

// App.js
import React from 'react';
import {Button,StyleSheet,View} from 'react-native';

const App = () => {
  return (
    <View
      style={styles.mainContainer}
      <Button
        title={"Enable Dark Mode"}
      />
    </View>
  );
};

mainContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white',
  },

});
Enter fullscreen mode Exit fullscreen mode

#Step 3: Create the following folders inside Root.
Create the following folders.

  1. actions
  2. reducers
  3. components

Inside the actions folder, create one file called types.js. Add the following line inside types.js.

export const ENABLE = 'ENABLE';
Enter fullscreen mode Exit fullscreen mode

The action type is the reducer’s operation type. Based on the action type, the reducer case will be executed, and we modify the state in such a way that it remains pure. So we create a copy of the existing state and return a new state.

Now, create one more file called theme.js in the same directory.

// theme.js
import { ENABLE } from './types';
export const changeTheme = theme => {
  return {
    type: ENABLE,
    payload: theme
  }
}
Enter fullscreen mode Exit fullscreen mode

The changeTheme() function returns an action. Now, based on that action, the reducers function’s case is executed.

But, we need to connect this action to our App.js component somehow. Otherwise, we can not add the data to the Redux store. Also, we need first to create a store. But before, we also need to create a reducer function. So, first, create a reducer, then create a store and then connect the React Native application to the Redux store.

#Step 4: Create a Reducer function.

Inside reducers function, create one file called themeReducer.js. Add the following code inside it.

//themeReducer.js
import { ENABLE } from '../actions/types';

const initialState = { isEnable: false };

export default function (state = initialState, action: any){
 const { type, payload } = action;
 switch (type) {
    case ENABLE:
      return {
        ...state,
        isLoggedIn: payload,
      };
    default:
      return state;
  }
}
Enter fullscreen mode Exit fullscreen mode

So, here, we have defined the function called themeReducer that accepts the two arguments.

1. state
2. action

The first time, it will take the initial state of our application, and then we pass whatever argument; it takes that argument and operates based on the case execution. The second argument is action, which consists of type and payload. The payload is the place name; we have entered inside the text box. So it adds the text box’s value inside places array.

Remeber here; we have returned a new state and not existing state. So we have modified the state in a pure manner and not existing state.

#Step 5: Create a Combine Reducers.

Inside the reducer folder, create one file called index.js and add the following code.

//index.js
import { combineReducers } from "redux";
import themeReducer from "./themeReducer";

export default combineReducers({
  themeReducer,
});

Enter fullscreen mode Exit fullscreen mode

Step 6: Create a Redux Store.

Inside the root folder, create one file called store.js and add the following code.

//store.js
import { configureStore } from "@reduxjs/toolkit";
import { useDispatch } from "react-redux";
import {
  FLUSH,
  PAUSE,
  PERSIST,
  persistReducer,
  persistStore,
  PURGE,
  REGISTER,
  REHYDRATE,
} from "redux-persist";
import reduxStorage from "../Storage";
import rootReducer from "./reducer/index";

const persistConfig = {
  key: "root",
  version: 1,
  storage: reduxStorage,
  timeout: 0,
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }),
});

export const persistor = persistStore(store);
export const useAppDispatch = () => useDispatch();
// export type RootState = ReturnType;

export default store;

Enter fullscreen mode Exit fullscreen mode

Step 7: Pass the Store to the React Native app.

// index.js
import { AppRegistry } from 'react-native';
import React from 'react';
import App from './App';
import { name as appName } from './app.json';
import { Provider } from 'react-redux';
import configureStore from './store';
const store = configureStore()
const RNRedux = () => (
  <Provider store = { store }>
    <App />
  </Provider>
)
AppRegistry.registerComponent(appName, () => RNRedux);
Enter fullscreen mode Exit fullscreen mode

It is almost the same as React web application, in which we pass the Provider as a root element and pass the store, and then via react-redux’s connect() function, we can connect **the any react component to **redux store.

#Step 8: Connect React Native app to Redux store.
Finally, we connect our App.js component to the Redux store. For that, we need the connect() function from the react-redux library.

//app.js
import React from 'react';
import { Button,StyleSheet,View } from 'react-native';
import {useSelector} from 'react-redux';
import {useAppDispatch} from './App/Store/store';
import {changeTheme} from './App/actions/theme.js';

const App = () => {
  const theme = useSelector(state => state.theme);
  const dispatch = useAppDispatch();
  const [isEnabled, setIsEnabled] = React.useState(theme.darkTheme);
  const toggleSwitch = () => setIsEnabled(!isEnabled);

  React.useEffect(() => {
    if (isEnabled) {
      dispatch(changeTheme({isEnable: true}));
    }
    if (!isEnabled) {
      dispatch(changeTheme({isEnable: false}));
      console.log(isEnabled);
    }
  }, [isEnabled]);

  return (
    <View
      style={[
        styles.mainContainer,
        {backgroundColor: isEnabled ? 'black' : 'white'},
      ]}>
      <Button
        title={isEnabled ? 'Enable Light Mode' :  "Enable Dark Mode"}
        onPress={() => {
          toggleSwitch();
        }}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  mainContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white',
  },
});

export default App;

Enter fullscreen mode Exit fullscreen mode

Done...

Top comments (1)

Collapse
 
codewithvaibhavi profile image
codewithvaibhavi

Nice one! dude