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.
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.
React Hooks and Redux Hooks
To replace the higher-order component Redux hook API is used, “connect()” with hooks like “useDispatch” and “useSelector” as present React-Redux provides 3 hooks:
⦿ useSelector():
This can help you replace the mapStateToProps. The purpose is to extract the data from the ‘Redux’ store whenever function component renders.
⦿ useDispatch():
A replacement to mapDispatchToProps, it’s purpose is to return the reference to the dispatch object.
⦿useStore():
It helps to return the reference that was wrapped in Redux
Let’s Start with Installing/ How to Add Redux
"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" },
Source: Heartbeat
The very next step is to install the dependencies to use Redux and manage the state:
yarn add redux react-redux lodash.remove
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.
How to Add Action Types and Creators
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.
Actions are similar to the events in Redux.
To start with
src/ directory Create subdirectory – Redux Create a new file - notesApp.js. Now you have provided an additional ability to allow users to add notes. // Action Types
export const ADD_NOTE = 'ADD_NOTE' export const DELETE_NOTE = 'DELETE_NOTE'
If you are looking to implement redux with React Hooks in your React Native application, Contact the best React Native App Development Company now.
Let’s Move Ahead to Add a Reducer
To Create Reducers
Path: src / store / File: /ducks/example.js
The receiver of the action is addressed as a reducer; whenever an action takes place, the state of the application changes and the app’s state is done by reducers. Reducer functions based on the previous and initial state.
// 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
Source: Viblo
Redux Store
Basically, the Redux store is responsible for the following:
- Holds application state
- Allows access to the state via getState()
- Let the state be updated via dispatch(action).
- Provides permission to registers listeners via subscribe(listener)
Under the src folder, create a store.js file and configure it with the Redux store to define the initialState parameter.
/* * src/store.js * No initialState */import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from './reducers/rootReducer';export default function configureStore() { return createStore( rootReducer, applyMiddleware(thunk) ); }
Source: Medium
To Create Store
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.
/* src/index.js */import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux' import configureStore from './store';import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker';ReactDOM.render( < Provider store={configureStore()} > < App /> < /Provider >, document.getElementById('root') ); registerServiceWorker();
Source: Medium
To Access the Global State
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.
The significant difference between the argument and the Hook is the selector will present any value in return not any object as a result.
Simply open the ViewNotes.js file.
// ...after rest of the imports import { useSelector } from 'react-redux'
Dispatching Actions
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.
import { useSelector, useDispatch } from 'react-redux'
To dispatch an action, define the following statement useSelectorHook in React Native:
const dispatch = useDispatch()
To trigger these events:
const addNote = note => dispatch(addnote(note)) const deleteNote = id => dispatch(deletenote(id)) FYI, here’s a code snipet of List.Item < List.Item title={item.note.noteTitle} description={item.note.noteValue} descriptionNumberOfLines={1} titleStyle={styles.listTitle} onPress={() => deleteNote(item.id)} / >
To Run the Application
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’s a complete snippet of code.
// ViewNotes.js import React from 'react' import { StyleSheet, View, FlatList } from 'react-native' import { Text, FAB, List } from 'react-native-paper' import { useSelector, useDispatch } from 'react-redux' import { addnote, deletenote } from '../redux/notesApp' import Header from '../components/Header' function ViewNotes({ navigation }) { // const [notes, setNotes] = useState([]) // const addNote = note => { // note.id = notes.length + 1 // setNotes([...notes, note]) // } const notes = useSelector(state => state) const dispatch = useDispatch() const addNote = note => dispatch(addnote(note)) const deleteNote = id => dispatch(deletenote(id)) return ( < > < Header titleText='Simple Note Taker' / > < View style={styles.container} > {notes.length === 0 ? ( < View style={styles.titleContainer} > < Text style={styles.title}>You do not have any notes< /Text > < /View > ) : ( < FlatList data={notes} renderItem={({ item }) => ( < List.Item title={item.note.noteTitle} description={item.note.noteValue} descriptionNumberOfLines={1} titleStyle={styles.listTitle} onPress={() => deleteNote(item.id)} / > )} keyExtractor={item => item.id.toString()} / > )} < FAB style={styles.fab} small icon='plus' label='Add new note' onPress={() => navigation.navigate('AddNotes', { addNote }) } / > < /View > > ) } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', paddingHorizontal: 10, paddingVertical: 20 }, titleContainer: { alignItems: 'center', justifyContent: 'center', flex: 1 }, title: { fontSize: 20 }, fab: { position: 'absolute', margin: 20, right: 0, bottom: 10 }, listTitle: { fontSize: 20 } }) export default ViewNotes
Wrapping Up
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 document. 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 hire React native developers to get the job done.