Reducers in Practice

Interactively visualize the complex state management in function components with the help of a real-life example.

Redux

The guiding principle of reducers should be known to those in the React community who have had exposure to Redux. Redux is a library that allows us to manage complex states comfortably and was the first point of call whenever handling local states became cumbersome and difficult to read. It also created a solution for “prop drilling,” which meant that previous props needed to be passed through multiple hierarchical layers.

Redux manages reducer functions and makes state and their dispatch functions available to those components that should read or modify the global state. The useReducer() Hook is React’s custom solution to realize complex state management using reducer functions.

Use case for reducers

A common use case for reducers forms the management of API requests. Common conventions dictate that three actions for each API request should be defined:

  1. An action that informs the application that the data is loading when the request has started
  2. An action that resets the loading state and, if the request has failed, can inform the state of an error
  3. An action that writes the data received by the API request into the state if it was successful

Example: Implementing useReducer() for account data using the GitHub API

Let’s use our previous account data example using the GitHub API to see the implementation of the useReducer() Hook:

Get hands-on with 1200+ tech skills courses.