How I Setup Redux Toolkit and RTK Query
wpcodevo
Posted on April 19, 2022
In this guide, I will show you how to set up Redux Toolkit and RTK Query with React and TypeScript the right way.
Visit Here for the full article: https://codevoweb.com/setup-redux-toolkit-and-rtk-query
Adding RTK Query to Redux Toolkit is not mandatory but when you combine both of them in a React project it brings out the true power of Redux Toolkit.
Technology Stack
- React
- TypeScript
- Redux Toolkit
- React-redux
- RTK Query
Prerequisites
- Comfortable with ES6 syntax and features
- Familiarity with React core concepts: JSX, Props, State, Functional Components
- Comfortable with Redux and its terminologies
How to Read this Tutorial Guide
This tutorial will focus on how to set up Redux Toolkit and RTK Query with React. I will assume you already have a good understanding of Redux and how to manage state with it in a React app.
For a more detailed explanation of what Redux is, how it works, and demos on how to use Redux Toolkit, check out the Redux overview tutorial.
The examples will be based on a typical Create React App project where all the code will be in the src folder. Also, I will provide some best practices to adopt when using Redux Toolkit with React.
The recommended way to Add Redux Toolkit to React
The recommended way to initialize a new app with React and Redux is by using the official Redux+JS template or Redux+TS template.
Creating a React app that uses Redux this way is a lot quicker and also prevents you from making mistakes.
# Redux + Plain JS template
npx create-react-app my-app --template redux
# Redux + TypeScript template
npx create-react-app my-app --template redux-typescript
Add Redux Toolkit to an Old React Project
This method is for those who want to add Redux Toolkit to their old React Projects.
If you also want to learn how to set up Redux Toolkit and RTK Query with React from scratch so that you can understand the ins and outs of Redux Toolkit then follow the tutorial step by step.
If you are starting a new React project with Redux then I recommend you follow the recommended way to add Redux Toolkit to React since it's quicker and easier to set up.
Am going to use Yarn as my package manager for this tutorial, you can use NPM if you are more comfortable with it. The package manager you use doesn't affect the code we will write.
Initialize a New React App
Before we start fetching and installing the required dependencies, let's first initialize a new React App if you don't have one.
Run this command to create a new React app with TypeScript.
# NPM
npx create-react-app redux-app --template typescript
# Yarn
yarn create react-app redux-app --template typescript
The project initialization process will take a couple of minutes depending on your internet speed so sit back and grab some coffee while Create React App does its job in the background.
Install Redux Toolkit and React-Redux
Fetch and install Redux Toolkit and React-redux in the project.
# NPM
npm install @reduxjs/toolkit react-redux
# Yarn
yarn add @reduxjs/toolkit react-redux
Redux Toolkit is already written in Typescript so we don't need to worry about installing its type definition files separately.
React redux has a dependency on @types/react-redux so the type definition file of the package will be automatically installed with it.
Create a Redux Store
Inside the src folder, create a redux folder and within this redux folder create a store.ts
file.
Now your folder structure should look somewhat like this.
redux-app/
├── node_modules/
├── public/
│ ├── favicon.ico
│ ├── index.html
│ ├── logo192.png
│ ├── logo512.png
│ ├── manifest.json
│ └── robots.txt
├── src/
│ ├── redux/
│ │ └── store.ts
│ ├── App.css
│ ├── App.test.tsx
│ ├── App.tsx
│ ├── index.css
│ ├── index.tsx
│ ├── logo.svg
│ ├── react-app-env.d.ts
│ ├── reportWebVitals.ts
│ └── setupTests.ts
├── .gitignore
├── package.json
├── README.md
├── tsconfig.json
└── yarn.lock
To create a store in Redux Toolkit, we have to use the configureStore
API which is a standard abstraction over the createStore
function but adds some good default configurations for a better development experience.
The configureStore function accepts a single configuration object with the following properties:
- reducer
- devTools
- middleware
- enhancers
- preloadedState
We are going to focus on the three essential properties (reducer, devTools and middleware) to configure the store.
import { configureStore } from '@reduxjs/toolkit'
export const store = configureStore({
reducer: {}
})
We don't need to provide the configureStore
with any additional typings.
Define the Root State and Dispatch Types
We need to extract the RootState and AppDispatch from the store and export them directly from the store.ts
file.
Inferring RootState and AppDispatch from the store itself means that they'll correctly update as you add more state slices, API services or modify middleware settings.
import { configureStore } from '@reduxjs/toolkit'
export const store = configureStore({
reducer: {}
})
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
Provide the Redux Store to the React App
Since the store has been created, we need to provide it to all our components from the top level of our application.
In the index.tsx
file, import the store from ./redux/store
and the <Provider>
component from react-redux.
Wrap the Provider component around the app component and pass the store as a prop to the Provider.
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
// 👇 Import Provider from react-redux and store from ./redux/store
import { Provider } from 'react-redux';
import { store } from './redux/store';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
{/* 👇 Provide the store as prop */}
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
Visit Here for the full article: https://codevoweb.com/setup-redux-toolkit-and-rtk-query
Posted on April 19, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
March 14, 2024
August 15, 2023