{"id":13292,"date":"2020-06-17T10:50:46","date_gmt":"2020-06-17T10:50:46","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/blog\/?p=13292"},"modified":"2024-06-06T06:58:36","modified_gmt":"2024-06-06T06:58:36","slug":"how-to-use-redux-with-react-hooks-in-react-native-application","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/blog\/how-to-use-redux-with-react-hooks-in-react-native-application","title":{"rendered":"How to Use Redux with React Hooks in React Native Application"},"content":{"rendered":"<style>\np{\n   width:100%;\n}\n<\/style>\n<p>The react-redux library has official support for the React Hooks as well as React Native applications to use Redux as a state management library. With more and more adoption of React Hooks and its ability to handle side effects and components, it is now regarded as a standard functional component pattern. Redux React hooks are available since the release of React version 16.8.x, and in this blog post, we will explore a structured pattern React Native Redux Hooks and how to use Redux with React Hooks.<\/p>\n<p>Redux-React hooks are available since the release of React version 16.8.x, and in this blog post, we will explore a structured pattern for Redux making use of React Native.<\/p>\n<h2>React Hooks and Redux Hooks<\/h2>\n<p>To replace the higher-order component Redux hook API is used, &#8220;connect()&#8221; with hooks like &#8220;useDispatch&#8221; and &#8220;useSelector&#8221; as present React-Redux provides 3 hooks:<\/p>\n<p>\u29bf useSelector(): <\/p>\n<p>This can help you replace the mapStateToProps. The purpose is to extract the data from the &#8216;Redux&#8217; store whenever function component renders.<\/p>\n<p>\u29bf useDispatch(): <\/p>\n<p>A replacement to mapDispatchToProps, it&#8217;s purpose is to return the reference to the dispatch object.<\/p>\n<p>\u29bfuseStore():<\/p>\n<p>It helps to return the reference that was wrapped in Redux <provider>. It is ideal to use in specific scenarios, like replacing reducers. <\/p>\n<h2>Let\u2019s Start with Installing\/ How to Add Redux<\/h2>\n<pre>\r\n\"dependencies\": {\r\n \"@react-native-community\/masked-view\": \"0.1.5\",\r\n \"expo\": \"~36.0.0\",\r\n \"react\": \"~16.9.0\",\r\n \"react-dom\": \"~16.9.0\",\r\n \"react-native\": \"https:\/\/github.com\/expo\/react-native\/archive\/sdk-36.0.0.tar.gz\",\r\n \"react-native-gesture-handler\": \"~1.5.0\",\r\n \"react-native-paper\": \"3.4.0\",\r\n \"react-native-reanimated\": \"~1.4.0\",\r\n \"react-native-safe-area-context\": \"0.6.0\",\r\n \"react-native-screens\": \"2.0.0-alpha.12\",\r\n \"react-navigation\": \"4.0.10\",\r\n \"react-navigation-stack\": \"2.0.10\",\r\n \"react-redux\": \"7.1.3\",\r\n \"redux\": \"4.0.5\"\r\n },\r\n<\/pre>\n<p style=\" text-align: center; font-size: 14px; font-style: italic;\">Source: <a href=\"https:\/\/heartbeat.fritz.ai\/using-redux-with-react-hooks-in-a-react-native-app-cc410a77f3e2\" rel=\"nofollow  noopener\" target=\"_blank\">Heartbeat<\/a><\/p>\n<p>The very next step is to install the dependencies to use Redux and manage the state:<\/p>\n<pre>yarn add redux react-redux lodash.remove<\/pre>\n<p>Here I am going to follow ducks for directory structure to manage Redux with React Hooks files as ducks let you have modular reducers in the application itself. There is no need to create separate files for types, actions, and action creators. All of these can be managed in one modular file, and if it demands to create more than one reducer, then you can simply define multiple header reducer files.<\/p>\n<p>How to Add Action Types and Creators<\/p>\n<p>While using React Redux with hooks, the state is characterized by JS object. It would be best if you considered an object as ready as it does not allow you to make changes in the state. This is the reason you need to take the help of actions. Actions are similar to the events in React Hooks with Redux.<\/p>\n<p>Actions are similar to the events in Redux. <\/p>\n<p>To start with <\/p>\n<pre>\r\nsrc\/ directory \r\nCreate subdirectory \u2013 Redux\r\nCreate a new file - notesApp.js.\r\nNow you have provided an additional ability to allow users to add notes. \r\n\/\/ Action Types\r\n<\/pre>\n<pre>\r\nexport const ADD_NOTE = 'ADD_NOTE'\r\nexport const DELETE_NOTE = 'DELETE_NOTE'\r\n<\/pre>\n<p class=\"boxed bg--secondary\" style=\"border: 1px solid #c7c7c7; box-shadow: 0 0 40px rgba(0, 0, 0, 0.2);\">If you are looking to implement redux with React Hooks in your React Native application, Contact the best <a href=\"https:\/\/www.bacancytechnology.com\/react-native-app-development\" target=\"_blank\" rel=\"noopener\">React Native App Development Company<\/a> now.<\/p>\n<h2>Let&#8217;s Move Ahead to Add a Reducer<\/h2>\n<p>To Create Reducers<\/p>\n<pre>\r\nPath: src \/ store \/\r\nFile: \/ducks\/example.js\r\n<\/pre>\n<p>The receiver of the action is addressed as a reducer; whenever an action takes place, the state of the application changes and the app&#8217;s state is done by reducers. Reducer functions based on the previous and initial state. <\/p>\n<pre>\r\n\/\/ import the dependency\r\nimport remove from 'lodash.remove'\r\n\r\n\/\/ reducer\r\n\r\nconst initialState = []\r\n\r\nfunction notesReducer(state = initialState, action) {\r\n  switch (action.type) {\r\n    case ADD_NOTE:\r\n      return [\r\n        ...state,\r\n        {\r\n          id: action.id,\r\n          note: action.note\r\n        }\r\n      ]\r\n\r\n    case DELETE_NOTE:\r\n      const deletedNewArray = remove(state, obj => {\r\n        return obj.id != action.payload\r\n      })\r\n      return deletedNewArray\r\n\r\n    default:\r\n      return state\r\n  }\r\n}\r\n\r\nexport default notesReducer\r\n<\/pre>\n<p style=\" text-align: center; font-size: 14px; font-style: italic;\">Source: <a href=\"https:\/\/viblo.asia\/p\/su-dung-redux-voi-react-hook-trong-react-native-gDVK2mPw5Lj\" rel=\"nofollow  noopener\" target=\"_blank\">Viblo<\/a><\/p>\n<h2>Redux Store<\/h2>\n<p>Basically, the Redux store is responsible for the following:<\/p>\n<ul class=\"bullets\">\n<li>Holds application state<\/li>\n<li>Allows access to the state via <a href=\"https:\/\/redux.js.org\/api-reference\/store#getState\" rel=\"nofollow  noopener\" target=\"_blank\">getState()<\/a><\/li>\n<li>Let the state be updated via <a href=\"https:\/\/redux.js.org\/api-reference\/store#dispatch\" rel=\"nofollow  noopener\" target=\"_blank\">dispatch(action)<\/a>. <\/li>\n<li>Provides permission to registers listeners via <a href=\"https:\/\/redux.js.org\/api-reference\/store#subscribe\" rel=\"nofollow  noopener\" target=\"_blank\">subscribe(listener)<\/a> <\/li>\n<\/ul>\n<p>Under the src folder, create a store.js file and configure it with the Redux store to define the initialState parameter.<\/p>\n<pre>\r\n \r\n\/*\r\n * src\/store.js\r\n * No initialState\r\n*\/import { createStore, applyMiddleware } from 'redux';\r\nimport thunk from 'redux-thunk';\r\nimport rootReducer from '.\/reducers\/rootReducer';export default function configureStore() {\r\n return createStore(\r\n  rootReducer,\r\n   applyMiddleware(thunk)\r\n );\r\n}\r\n<\/pre>\n<p style=\" text-align: center; font-size: 14px; font-style: italic;\">Source: <a href=\"https:\/\/medium.com\/backticks-tildes\/setting-up-a-redux-project-with-create-react-app-e363ab2329b8\" rel=\"nofollow  noopener\" class=\"broken_link\" target=\"_blank\">Medium<\/a><\/p>\n<h2>To Create Store<\/h2>\n<p>The Redux store is set up, but the application has no access to it. Using a provider from React binding react-redux, the store will be available to every component in the application. Here I am going to consider the store and children as props. <\/p>\n<pre>\r\n \r\n\/*\r\n src\/index.js\r\n*\/import React from 'react';\r\nimport ReactDOM from 'react-dom';\r\nimport { Provider } from 'react-redux'\r\nimport configureStore from '.\/store';import '.\/index.css';\r\nimport App from '.\/App';\r\nimport registerServiceWorker from '.\/registerServiceWorker';ReactDOM.render(\r\n < Provider store={configureStore()} >\r\n  < App \/>\r\n < \/Provider >,\r\n document.getElementById('root')\r\n);\r\nregisterServiceWorker();\r\n<\/pre>\n<p style=\" text-align: center; font-size: 14px; font-style: italic;\">Source: <a href=\"https:\/\/medium.com\/backticks-tildes\/setting-up-a-redux-project-with-create-react-app-e363ab2329b8\" rel=\"nofollow  noopener\" class=\"broken_link\" target=\"_blank\">Medium<\/a><\/p>\n<h2>To Access the Global State<\/h2>\n<p>To access state with Redux useSelector it is advisable to use the mapStateToProps inside connect(). It allows you to extract data from the Redux store state using a selector function.<\/p>\n<p>The significant difference between the argument and the Hook is the selector will present any value in return not any object as a result.<\/p>\n<p>Simply open the ViewNotes.js file.<\/p>\n<pre>\r\n\/\/ ...after rest of the imports\r\nimport { useSelector } from 'react-redux'\r\n<\/pre>\n<h2>Dispatching Actions<\/h2>\n<p>The Hook is only used to perform to dispatch function from the Redux store. Simply import it from the react-redux along with the action creators to dispatch an action. <\/p>\n<pre>\r\nimport { useSelector, useDispatch } from 'react-redux'\r\n<\/pre>\n<p>To dispatch an action, define the following statement useSelectorHook in React Native:<\/p>\n<pre>const dispatch = useDispatch()<\/pre>\n<h2>To trigger these events:<\/h2>\n<pre>\r\nconst addNote = note => dispatch(addnote(note))\r\nconst deleteNote = id => dispatch(deletenote(id))\r\n\r\nFYI, here\u2019s a code snipet of List.Item\r\n< List.Item\r\n  title={item.note.noteTitle}\r\n  description={item.note.noteValue}\r\n  descriptionNumberOfLines={1}\r\n  titleStyle={styles.listTitle}\r\n  onPress={() => deleteNote(item.id)}\r\n\/ >\r\n<\/pre>\n<h2>To Run the Application<\/h2>\n<p>So far, you are good to go with running an application from the terminal window executing the command called expo start. For your reference, here&#8217;s a complete snippet of code.<\/p>\n<pre>\r\n\/\/ ViewNotes.js\r\nimport React from 'react'\r\nimport { StyleSheet, View, FlatList } from 'react-native'\r\nimport { Text, FAB, List } from 'react-native-paper'\r\nimport { useSelector, useDispatch } from 'react-redux'\r\nimport { addnote, deletenote } from '..\/redux\/notesApp'\r\n\r\nimport Header from '..\/components\/Header'\r\n\r\nfunction ViewNotes({ navigation }) {\r\n  \/\/ const [notes, setNotes] = useState([])\r\n\r\n  \/\/ const addNote = note => {\r\n  \/\/ note.id = notes.length + 1\r\n  \/\/ setNotes([...notes, note])\r\n  \/\/ }\r\n\r\n  const notes = useSelector(state => state)\r\n  const dispatch = useDispatch()\r\n  const addNote = note => dispatch(addnote(note))\r\n  const deleteNote = id => dispatch(deletenote(id))\r\n\r\n  return (\r\n    < >\r\n      < Header titleText='Simple Note Taker' \/ >\r\n      < View style={styles.container} >\r\n        {notes.length === 0 ? (\r\n          < View style={styles.titleContainer} >\r\n            < Text style={styles.title}>You do not have any notes< \/Text >\r\n          < \/View >\r\n        ) : (\r\n          < FlatList\r\n            data={notes}\r\n            renderItem={({ item }) => (\r\n              < List.Item\r\n                title={item.note.noteTitle}\r\n                description={item.note.noteValue}\r\n                descriptionNumberOfLines={1}\r\n                titleStyle={styles.listTitle}\r\n                onPress={() => deleteNote(item.id)}\r\n              \/ >\r\n            )}\r\n            keyExtractor={item => item.id.toString()}\r\n          \/ >\r\n        )}\r\n        < FAB\r\n          style={styles.fab}\r\n          small\r\n          icon='plus'\r\n          label='Add new note'\r\n          onPress={() =>\r\n            navigation.navigate('AddNotes', {\r\n              addNote\r\n            })\r\n          }\r\n        \/ >\r\n      < \/View >\r\n    <\/ >\r\n  )\r\n}\r\n\r\nconst styles = StyleSheet.create({\r\n  container: {\r\n    flex: 1,\r\n    backgroundColor: '#fff',\r\n    paddingHorizontal: 10,\r\n    paddingVertical: 20\r\n  },\r\n  titleContainer: {\r\n    alignItems: 'center',\r\n    justifyContent: 'center',\r\n    flex: 1\r\n  },\r\n  title: {\r\n    fontSize: 20\r\n  },\r\n  fab: {\r\n    position: 'absolute',\r\n    margin: 20,\r\n    right: 0,\r\n    bottom: 10\r\n  },\r\n  listTitle: {\r\n    fontSize: 20\r\n  }\r\n})\r\n\r\nexport default ViewNotes\r\n<\/pre>\n<h2>Wrapping Up<\/h2>\n<p>The additional hooks such as useDispatch and useSelector Redux not only eliminates the need to write ample of boilerplate code but also provides the additional advantages of using functional components. To understand more in detail about how to use React Redux Hooks in React Native application, please refer to their official <a href=\"https:\/\/react-redux.js.org\/next\/api\/hooks\" rel=\"nofollow noopener\" target=\"_blank\">document<\/a>. If you are planning to hire React Native developers, with the relevant skillset who can help you implement Redux Hooks in your React-Redux application, then you have landed on the right page. We are a globally renowned react native development company and can help you build visually stunning and future-proof mobile app solutions. Based upon your preference and convenience <a href=\"https:\/\/www.bacancytechnology.com\/hire-react-native-developer\" target=\"_blank\" rel=\"noopener\">hire React native developers<\/a> to get the job done.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The react-redux library has official support for the React Hooks as well as React Native applications to use Redux as a state management library. With more and more adoption of React Hooks and its ability to handle side effects and components, it is now regarded as a standard functional component pattern. Redux React hooks are [&hellip;]<\/p>\n","protected":false},"author":170,"featured_media":13299,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"inline_featured_image":false,"_lmt_disableupdate":"no","_lmt_disable":"","footnotes":""},"categories":[714,1364],"tags":[],"coauthors":[2430],"class_list":["post-13292","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-react-native","category-application-development"],"acf":[],"modified_by":"Chandresh Patel","_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts\/13292","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/users\/170"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/comments?post=13292"}],"version-history":[{"count":0,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts\/13292\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/media\/13299"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/media?parent=13292"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/categories?post=13292"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/tags?post=13292"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/coauthors?post=13292"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}