A Better Data fetching Approach using Redux Toolkit & RTK Query

Usama Bin Khalil
5 min readAug 23, 2022

--

Redux Toolkit is an opinionated toolset for efficient Redux development created by the Redux team. It is the standard and recommended way to write Redux logic and manage state in your JavaScript applications. React and Redux is believed to be the best combo for managing state in large-scale React applications.
However, with time, the popularity of Redux has fallen due to the complexity of configuring a Redux store. Also the fact Redux requires too much boilerplate code. Redux Tool Kit solves these problems. It provides some options to configure the global store and create both actions and reducers more streamlined by abstracting the Redux API as much as possible.

In this article, we will see try to explore it

RTK Query Overview

RTK Query is a powerful data fetching and caching tool. It is designed to simplify common cases for loading data in a web application, eliminating the need to hand-write data fetching & caching logic yourself.

RTK Query is an optional addon included in the Redux Toolkit package, and its functionality is built on top of the other APIs in Redux Toolkit.

Initializing store

To initialize redux store a function by redux toolkit “configureStore” will replace the previous “createStore” function. It takes an object as a parameter with two properties.

configureStore: Creates a Redux store instance like the original createStore from Redux, but accepts a named options object and sets up the Redux DevTools Extension automatically.

  • A reducer:{object},
  • A middleware:[array or function that returns an array of middlewares].

Create Slice

  • createAction: Accepts an action type string and returns an action creator function that uses that type.
  • createReducer: Accepts an initial state value and a lookup table of action types to reducer functions and creates a reducer that handles all action types.
  • createSlice: Accepts an initial state and a lookup table with reducer names and functions and automatically generates action creator functions, action type strings, and a reducer function.

Handling async flows

To handle async actions Redux toolkit provides createAsyncThunk
which accepts a string identifier and a payload creator callback that performs the actual async logic and returns a promise that will handle the dispatching of the relevant actions based on the action types that we can handle in our reducers.

Unlike traditional data flows, actions handled by createAsyncThunk will be handled by the section extraReducers inside a slice. Inside extraReducers, we can handle both resolved (fulfilled) and rejected (rejected) states.

useSelector() and useDispatch

This store can be directly used from the component through redux APIs using useSelector and useDispatch.

Redux Toolkit Query

RTK Query uses queries and mutations to improve data fetching and caching.
It provides inbuilt support for error handling and optimistic updates.

  • Queries — This is the most common use case for RTK Query. You can use query operations with any data fetching library of your choice.
  • Mutations — A mutation is used to send updates to the server and replicate the same in the local cache.

In the above code, we have some additional attributes to make things easier:

  • transformResponse Allows manipulation of the data returned by a query or mutation.
  • keepUnusedDataFor To configure the data expiration time.
  • tagTypes — These tags will be used by RTK Query as keys to cache data.
  • invalidatesTags — These tags will be used to invalidate the cached data when a mutation occurs.

Finally, you can export the Query(useGetUsersQuery) and the Mutation(useCreateUserMutation) from this API.

Use[…..]Query Hook

Query basically used for “GET” method. This hook will return some properties (objects and boolean). DE-structure them using aliases to avoid contradiction as there will be use cases where more than one query is used in the same component.”refetch” is the function to call the query again explicitly (as it will be called once on page load). You can change the calling behavior using the “skip” (boolean) flag, pass in an object as 2nd argument i.e. use[…]Query(undefined if no params,{skip: true}) (will skip running the query on render).

  • isLoading: the Query is currently loading for the first time. No data yet.
  • isFetching: Query is now fetching but might have data from an earlier request.
  • isSuccess: The Query has data from a successful load.
  • isError: The Query is currently in an “error” state.

use[….]Mutation Hook

Mutation returns an ARRAY, a function as the first element, and an object with boolean flags and errors as 2nd element. Query and mutation accept only one parameter (more than one could be pass as object properties).

Transform Response

Query provides a “transformResponse” function with three parameters, first is “apiResponse” object with the result of API, the second “meta” with headers, and other metadata of API(you can explore by logging), and third is “error”, errors of API in case of fetch failure.

Adding Caching Mechanism

Use the above ApiSlice in our store to cache data.

In the above example, We have imported the API created using, passed its reducerPath and reducer values to configureStore to initialize the store. After creating the store, we can consume it inside the components using Hooks.

You can find more information on the Redux Toolkit by referring to their documentation. RTK Query reduces all the hassle of writing code for fetching and caching logic.

--

--

Usama Bin Khalil
Usama Bin Khalil

Written by Usama Bin Khalil

My boring softwares are people’s fulltime job.

Responses (3)