Creating strongly-typed function component state with useReducer
In this lesson, we are going to learn how to create strongly-typed state with the 'useReducer' hook.
We'll cover the following
Implementing a basic useReducer #
The useReducer
hook is excellent for implementing complex state scenarios. It uses a Redux like pattern for state management where object literals called actions are passed into a function called a reducer to change state.
We are going to leverage useReducer
to manage the count state within a Counter
component. Open the CodeSandbox project by clicking the link below and let’s get started:
CodeSandbox useReducer starter project
First, we are going to create the action types that will be referred to in the reducer we will eventually create. We are going to have two actions for incrementing and decrementing the counter. Let’s create these below the State
type:
type Increment = {
readonly type: 'increment';
readonly incrementStep: number;
};
type Decrement = {
readonly type: 'decrement';
readonly decrementStep: number;
};
So, the actions will have a type
property, which uniquely defines the type of action that needs to be performed along with the amount that the counter will need to be incremented or decremented. We have used the readonly
keyword on the action properties so that they are immutable.
Is it possible to create these action types using an interface rather than a type alias?
Get hands-on with 1400+ tech skills courses.