codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

A Redux Reducer is like a Coffee Maker

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).

Redux is so popular and most of us have either used it in some projects or have heard of it. Reducers are functions that are part of the Redux pattern and play a crucial role.

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

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.

function(state, action) => newState

A reducer should always follow the following rules:

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

Reducers are Pure Functions

Now what are pure functions?? Aren’t all functions that are written well pure??

Not long ago, I learned about what pure functions are and how they are supposed to work. They are quite simple and have the following rules to qualify as pure.

  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.

Now let’s talk about the requirement two on 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

Now we can’t always write functions that don’t have side-effects but if there is a side-effect then the function does not qualify as a pure function.

Using the Object Spread Operator inside your 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.

This is far easier and readable than using the Object.assign() method.

What makes Reducers in Redux shine?

After integrating redux within some of my more complex react native apps, I realised that the code was starting to look better.

Reducers are the major portion of the redux integration and hold a lot of the business logic. And since redux enforces that the reducers have to be pure functions with no side-effects we end up with very elegant and simple functions that are easily maintainable.

Writing clean reducers result in code that is easy to maintain, test and debug.

Imagine writing unit tests for functions that do only one thing, and don’t depend on the outside world. That is what well written reducers can provide.

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.

Multiple Reducers as your app grows

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 will have multiple reducers separated by functionalities.

You could have a reducer to handle all of the user information, another one to handle login and security and so on.

The example below shows the initialization of two reducers. The combineReducers from the redux library handles aggregation of all the reducers in the app. The aggregation is then passed to create the single redux store.

import { createStore, combineReducers } from 'redux';  // The User Reducer 
const userReducer = function(state = {}, action) {
return state
}
// The Login Reducer
const loginReducer = function(state = {}, action) {
return state
}
// Combine Reducers
const reducers = combineReducers({
userState: userReducer,
loginState: loginReducer
})
const store = createStore(reducers)

When we have multiple reducers, each reducer gets passed its respective subsection of the overall state and not the entire store’s state. Once the reducers do their work they return the new state of each of their subsections to the store.

I am Adhithi Ravichandran a Software Consultant working on React Native Apps. I am also a Pluralsight Author and love teaching. You can checkout my latest course on React Native from pluralsight below:

https://www.pluralsight.com/courses/react-native-big-picture

For more information and posts from me visit http://adhithiravichandran.com/ and follow me on twitter https://twitter.com/AdhithiRavi.

✉️ Subscribe to CodeBurst’s once-weekly Email Blast, 🐦 Follow CodeBurst on Twitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Adhithi Ravichandran

Software Consultant, Author, Speaker, React|Next.js|React Native |GraphQL|Cypress|Playwright Dev & Indian Classical Musician

Responses (1)

Write a response