Tutorials on React Redux

Learn about React Redux 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

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. 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. Define types for the store state and todo items: Then, create a default value for the store: 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: Now we can add a reducer for todos: 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. When everything is done, we can create a store: The react-redux package has a Provider component that lets you connect your components with the store. 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: For accessing the state value, react-redux has a useSelector hook. It is best to use useSelector than useStore to avoid unnecessary re-renders. 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.