Search⌘ K
AI Features

React and TypeScript: `useReducer` Hook

Explore implementing a common data fetching pattern in React using the useReducer hook combined with TypeScript. Learn how to type reducer actions safely with discriminated unions and represent loading, success, and error states effectively. Understand how to centralize state updates for cleaner code and improve type safety by modeling component state as a state machine.

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 ...