A Beginner’s Guide to Redux Toolkit Query/RTK Query

17 / Aug / 2023 by Simranjeet Kaur 0 comments

RTK Query is a set of utilities, a powerful data fetching and caching tool. It is an additional package provided by Redux Toolkit that enhances Redux by adding data fetching and caching capabilities.  Data fetching and state management are simple to incorporate in the Redux application by the smooth integration with Redux Toolkit.

Key Aspects of RTK Query – 

  • Fetch loading
  • Error handling
  • Automatic Caching

RTK Query primarily consists of two API’s – 

  • createApi()
  • fetchBaseQuery()

createApi() – To use RTK Query we must construct an ‘API Slice’ centrally, in which all the API endpoints that our application requires are listed. This ‘API Slice’ structure consists of all the Redux logic that enables us to fetch and cache data easily, createApi() takes an object parameter with {baseQuery, tagTypes, reducerPath, endpoints} as the configuration options.

fetchBaseQuery() – It is a compact fetch wrapper designed to streamline API requests & responses in Redux Toolkit and is passed to the baseQuery field in the createApi().

Query and Mutation Endpoints  – 

In RTK Query, The API endpoints are defined by returning the object inside the endpoints section of the createApi().All the endpoints are defined ahead of time and are created against the same baseUrl specified inside the baseUrl field of the fetchBaseQuery().

There are two types of endpoints –  Query and Mutation. Query Endpoint is used while fetching or caching data from the server and Mutation is used while sending an update to the server. All the fields of the endpoints are defined using the builder.query() or builder.mutation() method.

Redux Toolkit Hooks – 

RTK Query automatically generates hooks for every endpoint defined, based on the name of the endpoint in the service definition. These auto-generated hooks can be directly imported inside the UI component for data-fetching. 

Caching Data using RTK Query – 

In order to prevent re-fetching the same data repeatedly, caching is used. Thus, the caching functionality allows to reuse the already fetched data or cached data until the database is not changed. 

But we may need not to use the cached data or fetch fresh data according to the use case. So, we use Cache Invalidation to re-fetch the data. 

Cache Invalidation is achieved using the  – 

  • tagTypes – a tag or name is given to an apiSlice to manage the caching and invalidation behavior.
  • provideTags – a query consists of a provide tag that determines which tag is attached to the cached data returned by the query
  • invalidateTags – a mutation consists of an invalidate tag that determines which cached data is to be invalidated or re-fetched.

CRUD Operations using RTK Query –

Step 1. Create a React Project 

npx create-react-app demo-app

Step 2. Install required libraries 

npm install react-redux @reduxjs/toolkit bootstrap

Step 3. Create a mock JSON Server. 

  • Create a json file -> ‘db.json’ in the application
  • Install json server using  -> npm install -g json-server
  • Start the json server using -> json-server -–watch db.json -–port PORT_NUMBER

Step 4. Create an API Slice

Step 5. Connect API Slice to Redux Store

Step 6. Retrieve data using Query Endpoint

This Query Endpoint is used to fetch all the data from the database i.e db.json file and display a list of all the list items. Here, useGetProductsQuery is an auto-generated query hook that provides data, isLoading, isSuccess, isError, error properties. Data property of the hook can be used to fetch & display the data inside the UI component.

Step 7. Update Operation using Mutation Endpoint

Mutation endpoint is used to add a new item in the list and delete an item. useAddProductMutation and useDeleteProductMuatation are the mutation hooks.

Step 8. Use RTK hooks inside Components

The RTK Query and Mutation hooks are imported inside the required UI React Components for fetching and updating the data.

With the above RTK Query implementation the following Redux implementation steps have been eliminated – 

  • No need to create multiple action creators for each fetch request, as there is a single API service for the entire baseUrl.
  • Creating multiple reducers have been removed. 
  • We can retrieve data directly without having to dispatch actions or use selectors inside the UI components.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *