What is a Reducer in React?

A reducer in the context of a React application is a function that specifies how the state should change in response to actions that, for example, a user takes on the UI (e.g. submitting a form). In the following example file, from a contact manager app I’m building, you can see how a reducer works.

import {
  ADD_CONTACT,
  DELETE_CONTACT,
  SET_CURRENT,
  CLEAR_CURRENT,
  UPDATE_CONTACT,
  FILTER_CONTACTS,
  CLEAR_FILTER
} from '../types';

export default (state, action) => {
  switch (action.type) {
    case ADD_CONTACT:
      return {
        ...state,
        contacts: [...state.contacts, action.payload]
      };
    default:
      return state;
  }
};

On lines 1 - 9 a list of action types is imported from a global types file. Lines 11 - 21 comprise the whole of the reducer function being exported. On lines 12 - 20, a vanilla JS switch statement is used to define the reducer.

On line 15, the current state is spread and on line 16 we spread the contacts currently in state and add to it the new contact contained in the payload dispatched from the ADD_CONTACT action. Finally, the new current state is returned and accessible across the app’s components.

Here’s the GitHub repo for this project so you can check out the other files that make this work.

Show Comments

Get the latest posts delivered right to your inbox.