redux in react

redux in react  

https://www.mindbowser.com/redux-saga-vs-redux-thunk/

https://dev.to/raaynaldo/redux-toolkit-setup-tutorial-5fjf

The main feature of Redux is to manage and update the state of an application.

React Redux is the official React binding for Redux. It allows React components to read data from a Redux Store, and dispatch Actions to the Store to update data. Redux helps apps to scale by providing a sensible way to manage state through a unidirectional data flow model

Installation

npm install @reduxjs/toolkit react-redux

Create a Redux Store

import { configureStore } from '@reduxjs/toolkit';

export default configureStore({
  reducer: {},
});

Create a Redux State Slice

The main idea here is Slice will produce an action that we will use for dispatch and a reducer that we will use in configureStore.

src/features/todo/todoSlice.js\


Implementing useSelector and useDispatch in React Components

What is useSelector?

The useSelector hooks allow you to extract data or the state from the Redux store using a selector function. 

when an action is performed, the useSelector() hook will compare the results of the previous and current selector values and if they are different then the component is bound to re-render otherwise it stays the same.

The function will be called with the entire redux store state as an argument and runs whenever the functional components render the page. The useSelector() hook will subscribe to the redux store and runs whenever an action is dispatched.

useSelector

I mentioned before that if you want to get the state you will use a selector. This is how you can access the redux state.


useDispatch

Lastly, if we want to modify the global state we need to useDispatch and the action that we already created in slice.

What is Redux?

Redux is a state management library and can be used with any library or framework. It is an open-source, cross-platform library for managing the application states. Redux is widely and easily used in many libraries, React, React-native, and others. The primary use of Redux is that we can use a single application state as a global state, and interacting with the state of the application from any component is very easy if they are parent or child.

what is redux

Installation

npm install redux redux-logger react-redux –-save

Data Flow in Redux

Redux follows a unidirectional data flow. 3 major components are in redux structure‘actions’‘reducers’, and the ‘store’. Other components are ‘components(UI)’, ‘Middlewares’, ‘Redux Thunk’.

Actions: Actions are JavaScript objects that contain payloads of information that send data from the application to the redux store. These are the only information sources for the redux store. That means if any state change is necessary for any reason, the change required will be dispatched through the actions. It has a ‘type’ property that specifies the type of the action we are performing and can also have a ‘payload’ property used to send some data to redux stores.

Example of an Action object

Example of an Action object

Reducers: Reducers are functions that determine the changes in the application state and return the updated state. Actions describe something happening inside but don’t specify how the application’s state changes in response. When an action is dispatched for state change, the reducer has to make the necessary changes to the state and return the new state of the application. They take action as the argument and update the state inside the redux store.

Example of Reducer object

Example of Reducer object

Store: A redux store can be created With the help of reducers which holds the entire state of the application. It is recommended to use a single store for the entire application rather than having multiple stores, which will violate the use of redux, which only has a single store.

Components (UI): This is the section where the UI of the application is kept.

Middlewares: Redux middleware is a function that sits between action and reducer and can contact the dispatched action before reaching the reducer function. Popular middleware libraries which allow for side effects and asynchronous activities, there are Redux-Thunk and Redux-Saga.

What is Redux Thunk?

The middleware lets you call the action creators that return a function instead of the action object after receiving the redux store’s dispatch method, which is used to dispatch the regular synchronous actions inside a function’s body after the asynchronous operations have been completed.

The thunk is a concept of idea in programming where a function is used to delay the evaluation and calculation of an operation inside an app.

Installation

npm install redux-thunk –-save

Redux-thunk Store object example

Redux-thunk Store object example

Example of  Redux Thunk

Example of  Redux Thunk

What is Redux Saga?

Redux Saga library is another middleware that helps with API calls or side effects. It is the most popular competitor for Redux Thunk. Redux saga uses an ES6 feature called ‘Generators’, which helps write asynchronous code.

Generators are the functions that came with ECMAScript6 of javascript. Surprisingly, the generator functions can be paused, resumed, exited between the execution, and re-entered later during the operations. The name of the generator function name can be changed as per requirement. I have used the fetchDashboardSaga( ) function.

The benefit of Redux Saga compared to Redux Thunk is that you can more easily test your asynchronous data flow inside an application.

Installation

npm install redux-saga –-save

Example of Store object of redux-saga

Example of Store object of redux-saga

Example of Action

Example of Action

A Generator function is that function that does not execute it at once; instead, it returns an iterator object. The function body is executed when calling the method on an iterator object until the “yield” keyword is inside the function.

The next() method returns an object with a property called “value,” which has some value, and the yield property has returned it. A “done” property stands for whether a function execution is completed or not.

Working of Redux Saga?

Redux Saga listens that the actions dispatched and triggers an API call or any other side effect of your written code.

Below is an example of how we can call an API endpoint using Redux Saga.

Example of a redux-saga

Example of a redux-saga

By calling the put function, we can trigger actions just like we did with dispatch. It allows adjusting and handling of our reducer to handle our actions.

Saga works like a separate thread or by a background process, So for that is only responsible for making side effects inside APIs or API calls, unlike redux-thunk, in some cases, which uses callbacks that lead to situations like ‘callback hell.’ Every time with the async/await system, this problem can be minimized in redux-thunk.

Example of reducer object

Example of reducer object

Thunks can’t ever act in response to an action. On the other hand, Redux-Saga subscribes to the redux store and will trigger a saga to run, pause or continue when an action is dispatched.

Redux ThunkRedux Saga
Action creators may hold too many async logic functionsAction creators stay pure functions
Contains less boilerplate codesContains more boilerplate codes than Redux-Thunk
Difficult to scale up codesEasy to scale codes as compared to redux-thunk codes
Difficult to test async functions Easy to test as all async logic remains together
As compared to redux-saga, easy to understand logic, functions, conceptsDue to multiple concepts to learn like generator functions and redux-saga effects, etc. It is difficult to understand.

Comments