Understand The Redux Reducer

Understand The Redux Reducer

In this Redux Reducer tutorial, I am going to use that analogy and try to explain Reducers in Redux. Redux has been one of the most popular choice for state management in frontend applications. Redux is just a standalone state management library and you don’t have to use it for every single application. There are also other state management libraries like MobX that are popular which could be a good option as well. A reducer is a function that determines changes to an application's state

Redux has been one of the most popular choice for state management in frontend applications. But there has always been one recurring complaint about Redux. “Redux is hard to understand!” Many developers find redux confusing. I think some of this is because, Redux follows functional programming concepts that many developers are not used to. This could be the challenge to learn Redux.

In this post, I am going to try to break things up a bit, and get to the basics. At a conference talk in All Things Open last year, I spoke about Redux and integrating Redux to your application. I gave an analogy about the Redux reducer, which many of the attendees really appreciated. In this post I am going to use that analogy and try to explain Reducers in Redux.

What is a Reducer?

What is a Reducer ? And how do I write a reducer without messing up?

I like to think of a Reducer in Redux as a “Coffee Maker”. It takes in an old state and action and brews a new state (Fresh coffee).

I like to think of a reducer like a “coffee maker”. The coffee maker takes in coffee powder and water. It then returns a freshly brewed cup of coffee that we can enjoy. Based on this analogy reducers are functions that take in the current state (coffee powder) and actions (water) and brew a new state (fresh coffee).

Reducers are pure functions that take in a state and action and return a new state.

A reducer should always follow the following rules:

Given a set of inputs, it should always return the same output. No surprises, side effects, API calls, mutations.

What are Pure Functions?

Redux reducers are purefunctions. Now what are pure functions??

A function is considered pure, if it adheres to the following rules:

  1. The function always returns the same output if the same arguments are passed in.
  2. The function does not produce any side-effects.

We have all written pure functions in the past knowingly or unknowingly.
Take a look at a pure function below, that returns a sum of two numbers given two input arguments.

function sumOfNumbers(a, b) {
 return a + b;
}

The output of this function will always remain the same, if the same input arguments are passed in. Simple enough. Pure functions are simple building blocks that have a predictable behavior always. Hence they always return the same predictable output, without any external influence.

Here is a simple example, on what an impure function looks like.

var value = 5;
function impure(arg) {
    return value + 2 + 3;
}

Here the function is considered impure, because it is not using the argument that was passed to it. Instead, it uses an external value which is subject to change. Therefore, making the function impure due to external interference/side-effects.

What are Side-Effects?

Side effects occur anytime your function interacts with the outside world.

Some examples of common side-effects include:

  • Making an API call
  • Mutating data
  • console logs to the screen
  • Manipulating the DOM
  • Date.now() to get current date/time
  • async await calls/waiting for promises to resolve
  • math.random() to generate random numbers

Well, you may wonder how we can write functions without side-effects all the time. It is quite challenging to avoid side-effects altogether. All I am saying is, for a function to qualify as pure, as the name suggests, it should have no side-effects.

Never Mutate State Inside The Reducer

Once we understand what a pure function is, we are all set to start writing our reducers in redux.

We have to remember that we should never mutate state inside the reducer and this can be achieved with either the Object.assign() or the latest Object Spread (…) operator.

Never mutate state, always return a new copy of state.

Since the spread operator is easier to understand and is supported in the latest javascript versions, I am going to use it in my example.

The object spread operator is conceptually similar to the ES6 array spread operator.

Let’s walkthrough an example where you are going to rate this blog post. Our reducer will take the old state and the action. The action here is RATE_BLOG_POST. The reducer method _blogDetails() _will take the current state and action as the parameters and return a new state. Remember the coffee maker analogy again!

// Reducer
function blogDetails(state = initialState, action) {
  switch (action.type) {
     case RATE_BLOG_POST:
       return { 
         ...state, rating: action.rate 
       }
     default:
       return state
    }
 }

With the example above we are always going to return a new copy of the state. The spread operator (…) will ensure that there are no mutations of state within the reducer function.

Multiple Reducers For Larger Apps

Redux follows the single store principle to maintain one immutable store. But it allows you to have multiple reducers. As your app starts growing you can have multiple reducers separated by functionalities. This makes it easier to separate concerns across multiple reducers. In the example below we have two reducers A and B. And the combineReducer function from redux can be used to combine the reducers and pass them down to the single store.

import { createStore, combineReducers } from 'redux';  
// The A Reducer 
const AReducer = function(state = {}, action) {   
   return state 
}  
// The B Reducer 
const BReducer = function(state = {}, action) {   
   return state 
}  
// Combine Reducers 
const reducers = combineReducers({   
   AState: AReducer,   
   BState: BReducer 
})  
const store = createStore(reducers)
Benefits of Reducer

Reducers are the major portion of the redux integration and hold a lot of the business logic. Since reducers are designed to be pure functions, they carry a lot of benefits along.

  • Business logic is maintained in clean, simple and elegant functions because they are pure functions.
  • Reducers are pure functions, and therefore easier to maintain, test and debug.
  • It is also easy to extend and add additional functionality to the reducers.

Of course, writing clean pure functions is possible even if you do not use redux. But the fact that when we use redux in complex apps for state management, adhering to these principles is awesome.

Conclusion

Ultimately, Redux is just a standalone state management library and you don’t have to use it for every single application.

There are also other state management libraries like MobX that are popular which could be a good option as well.

Moreover with the addition of hooks and context you could possibly do away with state management libraries like Redux in React. Nevertheless, I like Redux and have used it in several projects successfully.

Originally published at https://programmingwithmosh.com

Hire React Js Developer from Expert React JS Development Company

Hire React Js Developer from Expert React JS Development Company

Are you looking to [hire React JS developer](https://www.mobiwebtech.com/react-js-development-company/ "hire React JS developer") from a prestigious and reliable React JS development company? Visit at Mobiweb Technologies here we have a big team...

Are you looking to hire React JS developer from a prestigious and reliable React JS development company? Visit at Mobiweb Technologies here we have a big team of expert React JS developers, you can hire them on an hourly, weekly or monthly basis for the successful completion of your dream project.

Learn React.js: Front-End Web Development for Beginners

Learn React.js: Front-End Web Development for Beginners

Learn React.js - Frontend Web Development for Beginners. In this React tutorial, you will learn the core fundamentals of React JS and Modern JavaScript so that you can start building lightning fast web apps using React JS. Learn Modern JavaScript and React JS from absolute scratch. Learn to make AJAX requests to get data from remote API and display into your web application. Learn React JS, which is one of the most exciting technology of recent time

Learn React.js - Frontend Web Development for Beginners - Web Development in 2019. In this video you will learn the core fundamentals of React JS and Modern JavaScript so that you can start building lightning fast web apps using React JS.

In this video, you will learn Modern JavaScript and React JS from absolute scratch. you will learn to make AJAX requests to get data from remote API and display into your web application.

So if you are ready to learn React JS, which is one of the most exciting technology of recent time

Thanks for watching

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

React - The Complete Guide (incl Hooks, React Router, Redux)

**☞ **Modern React with Redux [2019 Update]

**☞ **50+ Java Interview Questions for Programmers

**☞ **Top 100 Python Interview Questions and Answers

**☞ **100+ Basic Machine Learning Interview Questions and Answers

**☞ **Introduction to Java String Interview Questions and Answers

**☞ **Best 50 React Interview Questions and Answers in 2019

**☞ **Top 50+ SQL Interview Questions and Answers in 2019

**☞ **Best Java Microservices Interview Questions In 2019

**☞ **Best 50 Nodejs interview questions from Beginners to Advanced in 2019

**☞ **100+ Java Interview Questions and Answers In 2019

Top Vue.js Developers in USA

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.

We, at HireFullStackDeveloperIndia, implement the right strategic approach to offer a wide variety through customized Vue.js development services to suit your requirements at most competitive prices.

Vue.js is an open-source JavaScript framework that is incredibly progressive and adoptive and majorly used to build a breathtaking user interface. Vue.js is efficient to create advanced web page applications.

Vue.js gets its strength from the flexible JavaScript library to build an enthralling user interface. As the core of Vue.js is concentrated which provides a variety of interactive components for the web and gives real-time implementation. It gives freedom to developers by giving fluidity and eases the integration process with existing projects and other libraries that enables to structure of a highly customizable application.

Vue.js is a scalable framework with a robust in-build stack that can extend itself to operate apps of any proportion. Moreover, vue.js is the best framework to seamlessly create astonishing single-page applications.

Our Vue.js developers have gained tremendous expertise by delivering services to clients worldwide over multiple industries in the area of front-end development. Our adept developers are experts in Vue development and can provide the best value-added user interfaces and web apps.

We assure our clients to have a prime user interface that reaches end-users and target the audience with the exceptional user experience across a variety of devices and platforms. Our expert team of developers serves your business to move ahead on the path of success, where your enterprise can have an advantage over others.

Here are some key benefits that you can avail when you decide to hire vue.js developers in USA from HireFullStackDeveloperIndia:

  • A team of Vue.js developers of your choice
  • 100% guaranteed client satisfaction
  • Integrity and Transparency
  • Free no-obligation quote
  • Portal development solutions
  • Interactive Dashboards over a wide array of devices
  • Vue.js music and video streaming apps
  • Flexible engagement model
  • A free project manager with your team
  • 24*7 communication with your preferred means

If you are looking to hire React Native developers in USA, then choosing HireFullStackDeveloperIndia would be the best as we offer some of the best talents when it comes to Vue.js.