Press "Enter" to skip to content

Redux Reducers

In my current self directed learning path about React, I’m wrapping my head around Redux and how it’s used to manage state.

In C# we have an Aggregate() method that takes in a collection and spits out a single value. For instance:

IEnumerable<int ints = new List<int> { 4, 8, 12, 16 };
int result = ints.Aggregate((sum, val) => sum + val);

Can you guess what the value of result is? If you guessed (or knew) 40, you’d be correct.

  • First iteration: 4 + 8, returns 12
  • Second iteration: 12 + 12 returns 24
  • Third iteration: 24 + 16 returns the final 40

With regard to state and where Redux comes in, reducers take in an initial state, and an action, to determine the new state. Redux helps us streamline keeping track of state, so that it’s consistent across our apps. The below code snippet is from a reducer I created called alert.js. The import on the first line is simply importing the SET_ALERT and REMOVE_ALERT constants from my types.js file.

I create another constant and set my initialState equal to an empty array. The reducer function takes two params, current state & action and returns a new state based on action.type and action.payload.

import { SET_ALERT, REMOVE_ALERT } from '../actions/types';

const initialState = [];

export default function (state = initialState, action) {
  const { type, payload } = action;
  switch (type) {
    case SET_ALERT:
      return [...state, payload];
    case REMOVE_ALERT:
      return state.filter((alert) => alert.id !== payload);
    default:
      return state;
  }
}

An action is an object that contains two key/value pairs, type & payload. In Redux Reducers, action.type is required and action.payload is optional.

A core tenet of Redux is that it should never mutate state, so you see the use of the spread operator ...state which makes state immutable.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.