How to Use useReducer with TypeScript

The useReducer hook is a hook that allows you to create a state, update it, and share its data across different components. (Its core logic is similar to Redux.)

It takes a reducer-function and an initial state as arguments and returns a tuple of a new state and a dispatch function.

The reducer must extend the Reducer<State, Action> type, which is a function that takes a state and an action as arguments, updates the state, and returns the updated state:

State#

A state is usually an object with some data. Let's use a counter as an example.

If we want to keep track of a current counter value, we can create an object with a value field:

We will use this State type as a type parameter for the Reducer type later, and the initialState object will be the default value for the state.

Action#

An action is sort of like an event, which triggers the state updates. For example, a counter can have 2 actions: for increasing and decreasing its value.

Usually, an action is an object that has a type and payload. The type is like an ID of this action, and a payload is a data that the action transfers.

Reducer#

Now that we have a state and a set of actions we can create a reducer.

When a reducer is ready, we can use the useReducer hook.

useReducer#

Now we combine our initial state, reducer, and actions with a component:

Sources#