Tutorials on Redux Toolkit

Learn about Redux Toolkit from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

How to Use Thunks with Redux Toolkit and TypeScript

Last time we used Redux Toolkit to create a todo app. Since RTK is considered to be the standard way to write redux applications, we will use thunks with Redux Toolkit to write asynchronous logic as well. Thunks are a way to manage side effects when working with Redux. For instance, when we want to fetch some data from a server we need to perform an HTTP request. That request is a side effect because it interacts with the “outer world”. Redux itself doesn't know anything about side effects in an app. All the work is done in the redux-thunk middleware. It extends the store's abilities and lets you write async logic that interacts with the store. Redux Toolkit's configureStore function automatically sets up the thunk middleware by default. Right now we have a todo app that works synchronously, so we can only use the runtime storage to store the user data. In real-life applications, we would need to store user's data in some kind of persistent storage, on a server for example. Let's change our app a bit and, as an example, create a method to load todos from the server and show them. First of all, we're going to slightly refactor our previous code. We will extract our useTypedSelector from features/todos/TodoList.tsx to app/store.ts : ...This will help us to re-use this function in another component later. Also, we will extract some todos types into features/todos/types.ts : ...Which will help us to cover the API requests with types. As a backend, we will use JSON-placeholder . It allows us to fetch a list of todo-objects that we can render in our UI. The endpoint we use returns a list of todo-objects RTK provides a function called createAsyncThunk for creating thunks. Let's start with creating one: Let's write the real request logic using our placeholder backend: Cool, now it's working. However, the result we return is not typed. TypeScript yet doesn't know about the structure of data we return. For typing the result , we're going to need Todo type we extracted earlier: Okay, now our fetchTodos function doesn't take any argument. But let's think about a situation when we need to control the amount of fetched todos. We could use a function argument for that: The only thing left to cover is errors. Imagine that the server responded with a status 400. In this case, we would need to tell our users that todos aren't loaded and show the error message. Now, let's add our thunk to todosSlice . For that, we need to slightly change our TodosState : After it's done, let's define a selector for getting the status value: Finally, let's add reducers for handling our fetchTodos actions: The last thing to do is to use the fetchTodos thunk inside a component. Let's create a button, click on which will fetch a list of todos from a server. Now we can use this component to load todos from the server.

Thumbnail Image of Tutorial How to Use Thunks with Redux Toolkit and TypeScript

How to Use Redux Toolkit with TypeScript

The Redux Toolkit package is intended to be the standard way to write Redux logic. It simplifies the store creation and decreases the amount of boilerplate code. Let's rewrite the application we wrote in one of the earlier posts from scratch to see what will change. First of all, we need to create a new app. We can use Create React App with TypeScript template and then add Redux Toolkit or we can use a template that already includes everything we need. Now, if you look in the redux-toolkit-app directory you will see not only App.tsx but also 2 new directories: For now, let's clear the features directory, we won't need anything inside of it. Redux Toolkit introduces a new concept called a slice . It is an object that contains a reducer function as a field named reducer , and action creators inside an object called actions . Basically, a slice is a store part responsible for a single feature. We may think of it as a set of actions, a reducer, and an initial state. Slices allow us to write less code and keep feature-related code closer thus increasing cohesion . For our first slice, we're going to use a createSlice function. Let's start with re-creating typings for our store: Then, we create an initial state: And now, we can start creating a slice: The todosSlice object now contains actions and reducer fields. Let's export everything they have from the module: To use the state in our components, we need to create a state selector. For that, we need to define a RootState type. Let's change the app/store.ts a bit: Now return to todosSlice.ts and create a selector: The code of our component will be almost the same, except for imports and selector usage. Let's review it: And the list: We gain some advantages using RTK, such as: There are however disadvantages as well:

I got a job offer, thanks in a big part to your teaching. They sent a test as part of the interview process, and this was a huge help to implement my own Node server.

This has been a really good investment!

Advance your career with newline Pro.

Only $30 per month for unlimited access to over 60+ books, guides and courses!

Learn More