Throw Out Redux, Use Redux Toolkit

How to use Redux Toolkit with TypeScript

Adebola Adeniran
Better Programming

--

Photo by Tracy Adams on Unsplash

Out with the old, in with the new

A while back, when I started picking up Redux for the first time, I couldn’t believe how much code I needed to write to get anything to work. Frankly speaking, it scared me. And even though writing all the setup code from memory can make you feel pretty darn smart, after some time, it gets boring and you want to work with something that’s more intuitive and straightforward.

Redux can also be difficult for beginners to pick up and it certainly was difficult for me, well, until I discovered Redux Toolkit. It’s still surprising to me that it’s not as widely talked about as it should be and people seem to be stuck on old Redux.

If you’re looking to get started learning Redux or want a more intuitive way to write redux, RTK is the way to go.

In this article, I’ll show you how to set up RTK with TypeScript and React.

Why Use Redux Toolkit?

  • Type definitions — You can use it easily with TypeScript.
  • Mutate state directly — You no longer need to make a copy of state or to spread state. RTK comes with Immer which allows you to mutate state directly in the code while Immer does all the heavy lifting under the hood.
  • Redux Thunk — Writing async code in regular Redux requires installing additional middleware like Redux Saga or Redux Thunk. Not anymore. RTK comes bundled with Redux Thunk for all that async beauty.
  • One file — There is one file for all your reducers, actions, and action creators.
  • Redux Dev Tools — I can’t tell you how many times using Redux DevTools (you need to install the extension in your browser to use it) has helped me debug code faster and stopped me from having days where I want to smash my keyboard (no, I’d never do that — hopefully). RTK comes with Redux DevTools, which means you would never need to add any additional middleware to use it.

You can see the finished repo for this application on GitHub: https://github.com/onedebos/typescript-with-redux-example

Let’s Get Cracking — Setup

First, as always, create a new application called rtk-app using CRA with the TypeScript template.


npx create-react-app rtk-app — template typescript
cd rtk-app

Open up the app in your favorite code editor.

Set Up Redux Toolkit

Let’s start by installing the required packages. We will be building a simple application that makes a request to the NASA APOD API.

We need good ol’ React Redux and redux-toolkit itself. Redux Toolkit is written in TypeScript so no need to install an @types for the package.


npm install @types/react-redux react-redux @reduxjs/toolkit

You may need to run npm install one more time for CRA to pick up other @types declarations in your package.json.

Configure the Store

Redux is based on the idea of a single store, i.e., your entire state is stored in a single place.

Inside src/index.js, we will create our store.

Now, a couple of things to note:

We are using the configureStore method from RTK to create the store. The method takes an object with all your reducers as an argument.

We are using our photoSliceReducer, which is exported from a features/photos/PhotoSlice file (not yet created).

The RTK documentation encourages us to write all our state logic in a features folder with files named as “SomethingSlice.ts.”

Putting all our state logic in one file makes it easy for us to maintain our application and improves readability.

NB: You can pass as many reducers as you want to the store.

Set Up the Slice

Within the src directory, create a new folder called features/photo. Inside this, create a PhotoSlice.ts file.

This is where the magic happens. And all of that magic only relies on a single import.

First, we import createSlice, which is a function that takes one argument: an object with the slice name, initial state, and all your reducer functions.

We will also import PayloadAction to help us with type definitions for our payload. This way we can ensure that our payload always receives the correct types.

We export the reducer object that’s automatically available in photoSlice as a result of using the createSlice method. This is the reducer that we passed to our store when we created our store using configureStore earlier.

RTK also automatically generates our actions for us, and we can destructure them out of the photoSlice.actions object for use in our application.

photoSelector will allow us to select whatever state we want from the Redux store. We will come back to photoSelector in a bit.

Async Actions

Next, we need to make a request to the NASA APoD API to get photos for us to display. We will use axios to do this.

Remember, RTK provides Redux Thunk under the hood to allow us to write async code.

We’ve already imported axios in our PhotoSlice.ts, file but we need to install it. Install axios with the following:


npm install axios

Below the line where we exported our photosSelector, we can start writing some async actions.

Connect Components to the Redux Store

Let’s hook up our App component to the Redux store.

To connect App(or any other component) to the store, we do not need any of the connect function, HOCs, mapStateToProps, or any of that old stuff. Out with the old, in with the new, remember?

All we need to do is import the useSelector and useDispatch hooks, and we’re good to go.

To select whatever elements we want from the state, we pass the state (exported as photoSelector) to our useSelector hook.

We also have access to our thunk actions(getPhotos) that we exported from our PhotosSlice.ts file.

And with just a few lines of code, we’ve been able to hook up our App component to the Redux store. Isn’t that just amazing? Notice also how easy it is to read the code? Beautiful!

--

--