REDUX REDUCER

Soner Mezgitci
5 min readMay 12, 2021

The reducers specify how the app’s state changes in response to actions sent to store. The action only shows what kind of action was made for application but does not give any information about state changes. Reducers is giving information on how to change the state. Reducers is a function that accepts state and actions as arguments, and returns the next state of the application.(prevoiusState, action) => newState

const BUY_PASTA  = ‘ BUY_CAKE ’function buyPasta(){
return {
type: BUY_PASTA,
info : 'First redux action'
}
}

You can represent a reducer as previous state and action returning the new state. We need two arguments to write a reducer function. The state of the application before making any change and the action as we already defined as argument. Next steps to determine what our application state would look like.

(prevoiusState, action) => newState

Our target is to keep track of the numbers of the pasta on shelves. The state is a simple numeric value. If we remember the first principle of Redux, the state has to be represented by a single object. The object would have a property name numberOfPastas which is a numeric value.

const initialState = {numOfPasta: 10 }

We passed this initial state as the default value for the state parameter in the reducer. Application will start the initial state of the application passed in as an argument to reducer function. We will define both parameters in our reducer function as following.

const initialState = {numOfPasta: 10 }const reducer = (state = initialState, action) => {
}
}

We are returning to a new state in our reducer based on current state and the action. We will add the switch statement which the switch expression is action.

const initialState = {numOfPasta: 10}const reducer = (state = initialState, action) => {switch(action.type) {
case BUY_PASTA return {
numOfPasta: state.numOfPasta -1
}

default: return state
}
}

As you see, the action type is BUY_PASTA and we are going to return a new state of the application as a new object where the numberOfPasta is current numberOfPasta -1. If there was no action, return the state. We are not mutating the state , we are returning a new object. The reducer function is a pure function that accepts state and action as arguments and returns the next state of the application. The code in the example works well exactly how it is. You can try and debug by yourself. But most of the time the state has contained more than one property. Most important things are to copy the current state then update the property based on your desired value.

Copy State Object

We have a couple ways to copy state objects. But the most popular one is spread operator. The spread operator is a new addition to the set of operators in JavaScript ES6. It takes in an iterable (e.g an array) and expands it into individual elements.The spread operator is commonly used to make shallow copies of JS objects. Using this operator makes the code concise and enhances its readability.

const initialState = {numOfPasta: 10}const reducer = (state = initialState, action) => {switch(action.type) {
case BUY_PASTA return {
...state;
numOfPasta: state.numOfPasta -1
}

default: return state
}
}

Based on our example we are basically copying to state and updating only numberOfPasta:__. The other properties do not change. We completed our reducer function with copying and updating state property for our application.

What is the relation with Action & Reducer ?

An Action dispatching to our reducer. It’s sending an action object to the reducer. Reducer is responsible for taking an action object and decides based on the way how I set up my reducer. The reducer decides what I want to update about my current store.

Then reducer will return a new version of that store each time when I update data in our store. This is the reason why I had to pass reducer as an argument in Index.js file. It’s giving directions to my store when I am dispatched anytime. I want that action object to send to this reducer and update my store(value of the store). Action creators are exactly that — functions that create actions. It’s easy to conflate the terms “action” and “action creator”. In Redux, action creators simply return an action:

If you are still not clear, we can dive into other examples as follows.

function addTodo(text) {
return {
type: ADD_TODO,
text
}
}
PlayerReducer.jsexport default function playerReducer(state = {players: []}, action ) {
switch (action.type){
case 'FETCH_PLAYERS':
return {players: action.payload}
case 'ADD_PLAYER':
#We need another case to add player
return{...state, players: [...state.players, action.payload]}
case 'ADD_CONTRACT':
return {...state, newContract:action.payload}case'DELETE_CONTRACT':
return {...state, newContract:action.payload.contract}
default:
return state
}
}
let state= {numberOfPresents: 0}export function managePresents(state, action){switch(action.type){case 'INCREASE' :*return* {numberOfPresents: state.numberOfPresents +1}default:*return* state}}export function manageFriends(state = {friends: []} , action){switch(action.type){case 'ADD_FRIEND' :console.log(action)*return* {**...**state, friends: [**...**state.friends, action.friend]}case 'REMOVE_FRIEND' :const removeFriend = state.friends.findIndex(friend => friend.id === action.id)*return* ({**...**state,friends : [**...**state.friends.slice(0, removeFriend),**...**state.friends.slice(removeFriend + 1)]})default:*return* state;}}

Let’s break down

  1. line 1.2 * We are initialize state as a default Object with a key (friend) and set the value empty array.{friends: []
  2. line10* We are basically copy original array’s key and values with spread operator.
  3. its return a new state with this friend object added to the friends array.
  4. /line12 The findIndex() method returns the index of the first element in the array that satisfies
  5. the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.
  6. Found the friend with the matching id
  7. line 13/17 Thought of in another way, the reducer is really returning a new state with an array of friends that includes everyone except the removed friend.
  8. The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and
  9. end represent the index of items in that array. The original array will not be modified.

Summary

A reducer is a function that determines changes to an application’s state. It uses the action it receives to determine this change. We have tools, like Redux, that help manage an application’s state changes in a single store so that they behave consistently.

Why do we mention Redux when talking about reducers? Redux relies heavily on reducer functions that take the previous state and an action in order to execute the next state.

We’re going to focus squarely on reducers is in this post. Our goal is to get comfortable working with the reducer function so that we can see how it is used to update the state of an application and ultimately understand the role they play in a state manager, like Redux.

The Redux uses reducers to store and update state changes. The primary state update happens in the reducer function, and the value it returns sets the updated state of the application.

Understanding the role that reducers play in Redux should give you a better understanding of what happens underneath the hood. If you are interested in reading more about using reducers in Redux, it’s worth checking out the official documentation.

--

--

Soner Mezgitci

Software Engineer | Ruby on Rails | JavaScript | HTML5 | CSS | PostgreSQL | React | Redux