How to Use Redux with TypeScript

TypeScript can provide type-safety for reducers in your application, improves the documentation of your code, and overall improves long-term maintainability. Also, Redux officially recommends using static typing in their docs.

Basics#

Let's re-implement a todolist app. It is a basic example that many are familiar with, so it will be easier to focus on TypeScript part of a deal.

Create a new React app using Create React App with the TypeScript template:

First of all, we need to add dependencies to our app. We're going to need redux , react-redux, and types for the last one. We won't need an additional types package for Redux since it has its own type annotations.

When it's done, we can create a state.

Typing a State#

Define types for the store state and todo items:

Then, create a default value for the store:

Adding Actions#

When the state is created, we can create actions that will change the state. To be short, we will have only 2 actions that will add a new todo or mark them complete or incomplete.

When typings are completed, we create the actions themselves:

Adding a Reducer#

Now we can add a reducer for todos:

Combining Reducers#

If we had more than one reducer we would want to combine them using the combineReducers function:

It would allow us to create a single store instead of many for each feature.

Creating a Store#

When everything is done, we can create a store:

Using a Store Provider#

The react-redux package has a Provider component that lets you connect your components with the store.

Dispatching Actions#

Finally, when everything is ready, we can use our actions in components. react-redux has a set of hooks that can access the store and dispatch actions. The useDispatch hook lets us fire actions:

Using State Values#

For accessing the state value, react-redux has a useSelector hook. It is best to use useSelector than useStore to avoid unnecessary re-renders.

Conclusion#

This is the basics of typing the react-redux application. There are additional tricks that allow you to throw errors when an unknown action has been fired or to make type-checking even stricter. But we will cover them in a different post later.

Sources#