Redux Toolkit
Redux Toolkit is the official toolset to help developers work efficiently with Redux. It is designed to simplify the process of setting up Redux in a React app. Think of it like a pre-packed toolbox that provides the tools you need to manage state in a Redux app without having to deal with a lot of complex code.
Key Features:
- Official Toolset: It’s officially recommended and developed by the Redux team.
- Batteries-Included: It comes with everything you need (tools, features, and defaults) to make Redux development easier.
- Opinionated: It guides you with best practices for structuring Redux in your app.
Why Use Redux Toolkit?
Instead of writing complex Redux code from scratch, Redux Toolkit provides a streamlined approach that lets you focus on building your app rather than spending too much time on boilerplate code.
Installation & Setting Up a React Redux App
To get started with Redux Toolkit, you can quickly set up a React app with Redux using templates provided by Redux. This makes it easy to get going without worrying about manual configurations.
1. Using Vite + Redux Toolkit Template
Vite is a fast build tool for modern web apps. You can set up a new React app with Redux Toolkit using the Vite Redux+TS template. This template already includes everything needed for Redux and TypeScript integration.
- To create your app using the Vite template, run the following command:
npx degit reduxjs/redux-templates/packages/vite-template-redux my-app
2. Using Next.js with Redux Template
Next.js is a popular React framework. If you prefer using Next.js, you can use their official with-redux template, which already includes Redux Toolkit and React-Redux configurations.
- To create a Next.js app with Redux, run:
npx create-next-app --example with-redux my-app
These templates make setting up Redux in your React app super simple and save you from dealing with manual configurations.
Using Redux Toolkit in an Existing App
If you already have an existing React app or Node application and want to add Redux Toolkit, it’s simple to install.
Installation with NPM or Yarn:
Using NPM: To install Redux Toolkit, run the following command in your project folder:
npm install @reduxjs/toolkit
Using Yarn: Alternatively, if you’re using Yarn, you can install it with:
yarn add @reduxjs/toolkit
Once installed, Redux Toolkit will be ready to use in your project.
Using in the Browser:
If you want to use Redux Toolkit directly in the browser (without a module bundler like Webpack), the package includes a precompiled build. You can use it by adding the following <script>
tag to your HTML file:
This allows you to get started with Redux Toolkit in a browser-based app without additional setup.
Purpose
Redux Toolkit is designed to be the go-to solution for managing Redux logic in your applications. It was created to simplify Redux development by addressing three common challenges:
- Complex store configuration
- The need for many additional packages to make Redux work
- Excessive boilerplate code
While it doesn’t cover every single use case, Redux Toolkit offers tools that simplify the setup process and handle typical scenarios. It also includes utilities to help streamline your code.
That said, Redux Toolkit has a focused scope. It doesn’t tackle more complex concepts like reusable Redux modules, file organization, or managing entity relationships in the store.
Additionally, Redux Toolkit comes with a built-in feature called RTK Query, which provides powerful data fetching and caching capabilities. Although optional, RTK Query helps eliminate the need to manually write data fetching logic.
What's Included
configureStore(): Simplifies store setup by wrapping around
createStore
. It handles combining slice reducers, adding middleware, and includesredux-thunk
by default. It also enables the Redux DevTools Extension for debugging.createReducer(): Instead of using switch statements, you can create a lookup table with action types and case reducers. It also uses the Immer library to allow you to write mutative code for immutable state updates, like
state.todos[3].completed = true
.createAction(): Generates an action creator function based on a given action type string. The function has a
toString()
method, allowing it to replace the type constant.createSlice(): Combines
createReducer()
andcreateAction()
into one. It accepts reducer functions, a slice name, and an initial state, automatically generating a slice reducer with the necessary action creators and action types.combineSlices(): Merges multiple slices into a single reducer. It also supports lazy loading slices after initialization.
createListenerMiddleware(): Allows defining “listener” entries that contain callback effects. These callbacks run based on certain actions or state changes. It’s a lighter alternative to Redux async middleware like sagas or observables.
createAsyncThunk(): Takes an action type and a function that returns a promise. It automatically dispatches
pending
,resolved
, orrejected
action types depending on the promise status.createEntityAdapter(): Provides a set of reusable reducers and selectors for managing normalized data in the store.
createSelector(): A utility from the Reselect library that is re-exported for ease of use in Redux Toolkit.
RTK Query
RTK Query is an optional add-on within the @reduxjs/toolkit package, designed to handle data fetching and caching in your app. It offers a streamlined and powerful toolset for defining an API interface layer, simplifying common tasks such as loading data in web applications. By using RTK Query, you can eliminate the need to manually write data fetching and caching logic.
RTK Query leverages Redux Toolkit’s core and builds on top of Redux for its architecture. While you don’t need to be an expert in Redux or RTK to use RTK Query, it’s beneficial to explore the additional global store management features they provide. Additionally, integrating Redux DevTools is highly recommended as it works seamlessly with RTK Query to let you monitor and replay a timeline of your requests and cache behavior.
Accessing RTK Query:
import { createApi } from '@reduxjs/toolkit/query'
/* React-specific entry point that automatically generates
hooks corresponding to the defined endpoints */
import { createApi } from '@reduxjs/toolkit/query/react'
What's included
RTK Query includes these key APIs:
createApi()
: This is the core function of RTK Query. It allows you to define a set of endpoints and describes how to retrieve data from those endpoints. It also includes configuration for fetching and transforming that data. Typically, you should usecreateApi()
once per application, with the general rule of using one API slice per base URL.fetchBaseQuery()
: A lightweight wrapper around thefetch
API designed to simplify request handling. It’s recommended as the default base query for most use cases when working withcreateApi
.<ApiProvider />
: This component can be used as a Provider if you don’t have a Redux store already set up in your application.setupListeners()
: A utility function used to enable behaviors such asrefetchOnMount
andrefetchOnReconnect
, which are useful for managing data fetching and cache invalidation when certain conditions are met.
Contributing
Please refer to the Contributing Guide for detailed information on:
- The development process of Redux Toolkit.
- How to propose bug fixes and improvements.
- How to build and test your changes to the Redux Toolkit.
This guide provides you with step-by-step instructions to contribute effectively, whether you are reporting an issue, suggesting new features, or contributing code.
Frequently asked questions (FAQs) about Redux Toolkit
What is Redux Toolkit?
Redux Toolkit is an official, opinionated, and simple library designed to streamline Redux development. It provides tools and utilities that help developers write Redux logic with fewer lines of code and without having to deal with the complexity of manual configuration.
2. Why should I use Redux Toolkit?
Redux Toolkit simplifies Redux development by reducing boilerplate code, offering a set of good defaults, and providing useful features like the createSlice
function for handling actions and reducers in one place. It also includes built-in tools like Redux DevTools, which simplifies debugging.
3. What is the difference between Redux and Redux Toolkit?
Redux Toolkit is essentially a wrapper around Redux that provides a simpler, opinionated setup. While Redux requires you to manually configure the store, write action creators, and reducers, Redux Toolkit abstracts these complexities and offers built-in utilities like createSlice
, configureStore
, and createAsyncThunk
.
4. What is configureStore() in Redux Toolkit?
configureStore()
is a function in Redux Toolkit that simplifies the setup of the Redux store. It automatically configures Redux DevTools, adds middleware like redux-thunk
, and combines reducers in a more convenient way than manually configuring them.
5. What is createSlice()?
createSlice()
is a utility function that simplifies the process of writing reducers and action creators. It allows you to define the initial state and actions in one place, automatically generating the corresponding action creators and action types, saving time and reducing boilerplate.
6. What is createAsyncThunk()?
createAsyncThunk()
is a helper function that simplifies handling asynchronous actions in Redux. It automatically dispatches the appropriate action types (pending
, fulfilled
, rejected
) based on the promise returned by the action creator, making it easier to manage asynchronous logic.
7. Is Redux Toolkit required to use Redux?
No, Redux Toolkit is not required to use Redux. However, it simplifies many common patterns and reduces boilerplate. While you can still use Redux directly, Redux Toolkit is recommended as the official approach to Redux development because it makes your code cleaner and easier to maintain.
8. Can I use Redux Toolkit with React?
Yes, Redux Toolkit works seamlessly with React. It even has a React-specific entry point (@reduxjs/toolkit/query/react
) that provides hooks for interacting with the Redux store, making it easy to connect your Redux state with your React components.
9. What is createAsyncThunk used for?
createAsyncThunk
is used to handle asynchronous logic (like fetching data from an API) in a Redux store. It dispatches actions to reflect the current state of the request, such as loading, success, or error, and allows you to update the state based on those actions.
10. What is RTK Query and how is it related to Redux Toolkit?
RTK Query is a data-fetching and caching tool included within Redux Toolkit. It simplifies the process of fetching and caching data by providing powerful tools to define API endpoints, perform queries, and manage cache behavior automatically. It helps reduce the need for writing custom data-fetching code in your application.