...

/

React and TypeScript: `useReducer` Hook

React and TypeScript: `useReducer` Hook

This lesson is a detailed analysis of typing the `useReducer` hook in TypeScript. It also provides a great use case for discriminated unions and state machines.

Overview

In this lesson, we will implement a common data fetching scenario with the useReducer hook. We will see how to take advantage of TypeScript’s discriminated unions to correctly type reducer’s actions. Finally, we will introduce a useful pattern for representing the state of data fetching operations.

Do we need a reducer?

We will base our code on an example from the official React documentation. The demo linked from this article is a simple implementation of a very common pattern, fetching a list of items from some backend service. In this case, we’re ...