Search⌘ K
AI Features

Reducer Basics

Explore the basics of reducers in React by understanding how functions manage state and actions within TypeScript. This lesson helps you grasp the process of defining reducers, using action types, and integrating with React’s useReducer hook to simplify state management effectively.

At its most fundamental level, a reducer is simply a function that takes two arguments: the current state and an object representing an action that has occurred. The reducer returns the new state based on that action.

 A diagram showing how a reducer works
A diagram showing how a reducer works

Working of reducer

The following code is regular JavaScript, but it could easily be converted to TypeScript by adding any types to state and action:

Javascript (babel-node)
export const incrementAction = { type: 'Increment' };
export const decrementAction = { type: 'Decrement' };
export const counterReducer = (state, action) => {
if (action.type === 'Increment') {
return { count: state.count + 1 };
}
if (action.type === 'Decrement') {
return { count: state.count - 1 };
}
return state;
};
let state = { count: 1 };
state = counterReducer(state, incrementAction);
state = counterReducer(state, incrementAction);
state = counterReducer(state, decrementAction);
console.log(state); // Logs: { count: 2 }

Let’s explain the code sample above:

    ...