Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Typing Reducers with useReducer | Advanced React Patterns with TypeScript
TypeScript Essentials for React

bookTyping Reducers with useReducer

メニューを表示するにはスワイプしてください

When you use the useReducer hook in React, TypeScript allows you to precisely type both your reducer's state and the actions it can handle. This ensures your reducer logic is robust and less prone to errors. Begin by defining a type for your state object, which describes the data structure your reducer manages. For example, if you are building a simple counter, you might define your state type as:

type CounterState = {
  count: number;
};

The next step is to define the possible actions your reducer can handle. A recommended pattern is to use a discriminated union for your action types. This approach lets TypeScript enforce that every action type is handled explicitly, making your reducer safer and easier to maintain.

A discriminated union for action typing uses a common type property to distinguish between different action shapes. Consider the following example for a counter reducer:

type CounterAction =
  | { type: "increment" }
  | { type: "decrement" }
  | { type: "reset"; payload: number };

Here, each action is an object with a type property, and some actions (like "reset") can include additional data via a payload property. This structure allows TypeScript to narrow the action type inside your reducer function, providing type safety for both the action type and any associated data.

1. What is a discriminated union useful for in reducer action typing?

2. Why should you type both state and actions in useReducer?

question mark

What is a discriminated union useful for in reducer action typing?

正しい答えを選んでください

question mark

Why should you type both state and actions in useReducer?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 6.  2

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 6.  2
some-alt