The Talent500 Blog
How to Use Redux with React Hooks in React Native Application 1

How to Use Redux with React Hooks in React Native Application

With the popularity of React Hooks, the ability to manage a component’s state and side effects has become a prevalent trend in functional components. As an alternative to the ubiquitous connect() high order component, React Redux provides a set of Hook APIs.

The react-redux package provides official support for React Hooks and React Native apps that want to utilise Redux as a state management tool. Given the increasing prevalence of React Hooks and their ability to handle side effects and components, it is now considered a common functional component design. Since the release of React version 16.8.x, Redux React hooks have been available.

In this blog, let’s construct a small React Native app where a user may store notes.

If you know the basics of React Hooks and how to implement it with a basic navigation setup, you can continue from this one.

Install redux

If you cloned the repo from the previous example, check that the package’s dependencies are correct. The json file looks like this:

“dependencies”: {
“@react-native-community/masked-view”: “0.1.5”,
“expo”: “~36.0.0”,
“react”: “~16.9.0”,
“react-dom”: “~16.9.0”,
“react-native”: “https://github.com/expo/react-native/archive/sdk-36.0.0.tar.gz”,
“react-native-gesture-handler”: “~1.5.0”,
“react-native-paper”: “3.4.0”,
“react-native-reanimated”: “~1.4.0”,
“react-native-safe-area-context”: “0.6.0”,
“react-native-screens”: “2.0.0-alpha.12”,
“react-navigation”: “4.0.10”,
“react-navigation-stack”: “2.0.10”,
“react-redux”: “7.1.3”,
“redux”: “4.0.5”
},

To integrate and manage the state with Redux, now install the following dependencies from a terminal window.
yarn add redux react-redux lodash.remove

The directory structure used to organise Redux-related files will be based on the pragmatic method known as ducks. The duck’s design enables the use of modular reducers within the app itself. There is no need to create separate files for actions, types, and action creators. Instead, declare them all in a single modular file; however, if more than one reducer is required, specify several reducer files.

Adding creators and action types

When utilising Redux to manage the overall state of the application, the state is represented by a single JavaScript object. Think of this object as read-only, since you cannot make changes to this state directly. It requires actions to do so.

In Redux, actions are analogous to events. They can be activated by button presses, timers, or network requests.

To begin, establish a subfolder named redux under the src/ directory. Create a new file named notesApp.js within it.

Thus far, the programme allows the user to add notes. Let’s start by creating two action kinds and their creators in the newly generated files. The user will be able to remove an item from the ViewNotes screen using the second action type.

// Action Types
export const ADD_NOTE = ‘ADD_NOTE’
export const DELETE_NOTE = ‘DELETE_NOTE’

Next, for each action type, define action creators. The first will be triggered when the note is saved, and the second will be triggered when the note is deleted.

// Action Creators
let noteID = 0
export function addnote(note) {
  return {
    type: ADD_NOTE,
    id: noteID++,
    Note
  }
}
export function deletenote(id) {
  return {
    type: DELETE_NOTE,
    payload: id
  }
}

Adding a reducer

A reducer is who receives the action. The application’s state changes whenever an action is performed. The reducers are in charge of managing the application’s state.

A reducer is a pure function that determines the future state depending on the previous or starting state. If the state remains unaltered, it always returns the same result. It accepts two inputs (state and action) and must return the default state.

The initial state will be an empty array. When you’ve specified action creators, add the following. Likewise, at the top of the notesApp.js file that was installed at the start of this post, import the remove tool from the lodash.remove npm package:

// import the dependency
import remove from ‘lodash.remove’
// reducer
const initialState = []
function notesReducer(state = initialState, action) {
  switch (action.type) {
    case ADD_NOTE:
      return [
        …state,
        {
          id: action.id,
          note: action.note
        }
      ]
  case DELETE_NOTE:
      const deletedNewArray = remove(state, obj => {
        return obj.id != action.payload
      })
      return deletedNewArray
    Default:
      return state
  }
}
export default notesReducer

Configure a Redux store

A store is an object that connects actions and reducers. It delivers and maintains state at the application level rather than at the level of individual components. Redux does not have an opinion about which framework or library should utilise it.

When you’ve finished creating the reducer, add a new file named store.js to the src/redux/ directory. Import the function createStore from redux, as well as the app’s only reducer for the time being.

import { createStore } from ‘redux’
import notesReducer from ‘./notesApp’
const store = createStore(notesReducer)
export default store


Open the entry point file App.js and import the store as well as the react-redux npm package’s high order component (HOC) Provider to link this Redux store to the React Native app. This HOC assists you in passing the store down to the other components of the current app.

import React from ‘react’
import { Provider as PaperProvider } from ‘react-native-paper’
import AppNavigator from ‘./src/navigation’
import { Provider as StoreProvider } from ‘react-redux’
import store from ‘./src/redux/store’
// modify the App component

export default function App() {
  return (
    <StoreProvider store={store}>
      <PaperProvider>
        <AppNavigator />
      </PaperProvider>
    </StoreProvider>
  )
}

That’s all! The Redux store is fully set up and ready to go!

Accessing global state

The useSelector Hook is given to access state while managing it using Redux. It’s analogous to the mapStateToProps parameter supplied by connect (). It lets you use a selector function to pull data from the Redux store state.

The major difference between the Hook and the argument is that the selector may return any value as a result, not just an object.
1. Open the ViewNotes.js file
2. Import this Hook from react-redux

// …after rest of the imports
import { useSelector } from ‘react-redux’

Next, inside the ViewNotes functional component, instead of saving a notes array with the useState Hook, replace it with the following:

const notes = useSelector(state => state)

Dispatching actions


The useDispatch() Hook entirely refers to the Redux store’s dispatch function. This Hook is only used when an action has to be sent. Import it from react-redux, along with the addnote and deletenote actions from the redux/notesApp.js file.

import { useSelector, useDispatch } from ‘react-redux’

After the useSelector Hook, define the following sentence to dispatch an action:

const dispatch = useDispatch()

Next, to trigger these events, dispatch two operations named addNote and deleteNote:

const addNote = note => dispatch(addnote(note))
const deleteNote = id => dispatch(deletenote(id))

Because the naming convention for the addNote action is identical to that of the previous post’s helper function, there is no need to make any modifications inside the functional component’s return statement for this. But, the deleteNote action is brand new.

Add a prop onPress to List to remove a note from the displayed list. React-native-paper item UI component. This will provide the capability of removing an item from the list when the user touches it.

Below is the code snippet of List.Item component with changes. Also, ensure to modify the values of props: title and description.

<List.Item
  title={item.note.noteTitle}
  description={item.note.noteValue}
  descriptionNumberOfLines={1}
  titleStyle={styles.listTitle}
  onPress={() => deleteNote(item.id)}
/>

The advantage of  useDispatch hook is that it replaces mapDispatchToProps. Also it is not required to write boilerplate code to bind action creators with this hook now.

Conclusion

Other hooks like useDispatch and useSelector Redux not only minimise the need to create a lot of boilerplate code, but they also give the benefits of utilising functional components. Hence, while redux assists us in managing application state, this does not imply that you should use Redux in all of your projects. Other methods for handling state in our application include react-context, mobx, and libraries. But, before diving into the Redux components, it’s a good idea to brush up on your application development fundamentals. If the app state is regularly updated, and the logic to update that state is complicated, you might consider utilising redux. The programme has a medium or big codebase and may be worked on by a large number of individuals. You must examine how that condition changes throughout time.

 

0
Afreen Khalfe

Afreen Khalfe

A professional writer and graphic design expert. She loves writing about technology trends, web development, coding, and much more. A strong lady who loves to sit around nature and hear nature’s sound.

Add comment