DEV Community 👩‍💻👨‍💻

DEV Community 👩‍💻👨‍💻 is a community of 963,864 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Erik Smith
Erik Smith

Posted on

Basic Reducer Pattern

The basic concept of a reducer is to provide a pure function defining the types of operations you're planning to perform on the values of the current state.

A reducer performs one of a collection of actions using the values found in the current state, then outputs the next shape of state with those actions applied, as in (state, action) => next. The reducer does not actually update or alter the state itself, which is treated as an immutable moment in the application history. The expectation is that some other mechanism keeps track of the current state of the application from one moment to the next, typically in a store.

const count = 12;

const reducer = (state, action = { type: null, payload: null }) => {
  switch(action.type) {
    case 'INCREASE':
      return state + action.payload;
    case 'DECREASE':
      return state - action.payload;
    case 'MULTIPLY': 
      return state * action.payload;
    case 'DIVIDE':
      return state / action.payload;
    default:
      // It's common for a reducer to return the current state when action.type 
      // is unrecognized, but doing so invites difficult to decipher defects. 
      throw new Error(`Unhandled action type: ${action.type}`);
  }
};

console.log(reducer(count, {type: 'INCREASE', payload: 3 })) // 15
console.log(reducer(count, {type: 'DECREASE', payload: 2 })) // 10
console.log(reducer(count, {type: 'DIVIDE', payload: 3 })) // 4
console.log(reducer(count, {type: 'MULTIPLY', payload: 12 })) // 144
try {
    console.log(reducer(count, {type: 'UNKNOWN', payload: 100 })); // Throws an error we will catch!
} catch(e) {
    console.log(`We caught the error!`); // We catch it every time!
}
console.log(count); // 12 (count remains unchanged)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post