Tuesday, May 26, 2026

RTK Query

 It is an advanced data fetching and caching tool. It can fetch async data, cache and applies advanced features.

It comes with Redux toolkit.                                               

Why we need RTK?

Because it has a feature of caching and can automatically handle the responses.

To export as custom hook for query and mutation we need to add /react the end of "@reduxjs/toolkit/query" as "@reduxjs/toolkit/query/react". This way we can export query and mutation.

"@reduxjs/toolkit/query"  - For Redux only

"@reduxjs/toolkit/query/react" - For Redux and React both

A Reducer is a function that describes how tthe application state changes in response to an action.

We use createApi method to create a slice for RTK.

Managing queries in query parameter

(id) => `posts/${id}` 
and
`${city}?format=j1` 

setUpListeners - it is mandatory when used setupListeners(store.dispatch); in store.

it is used to get updated data when we return from any updated tabs.

Store helps to deal with local states. So we can also use ApiProvider instead of Provider from react-redux. 

without redux use ApiProvider.
<ApiProvider api={jsonPlaceholderApi}>
    <App/>
<ApiProvider/>

But we usually avoid it because we can have multiple api.

To save data for future we use keepUnusedDataFor: 20, to keep our data for specific time interval. Keeps data for 20 seconds. default is 30. can be added after reducerPath

OR

We can add it here

getPosts: builder.query({ keepUnusedDataFor: 20, query: () => "posts" }),

instead of query it can be any function name e.g. queryFn

If component using the data is unmounted then cached data will be deleted because it is no longer needed.

refetchOnFocus: true, - To get data when revisited to the page.

Youtube link: Learn RTK Query in 30 Minutes - React Redux Toolkit RTK Query Tutorial For Beginners

Github link: machadop1407/rtk-query-tutorial

Used for data fetching and caching. 
No need for createAsyncThunk and no manual reducer is needed.

We don't make slice because it has no reducer.

redux-toolkit/docs/rtk-query at master · reduxjs/redux-toolkit

For asyncActions we use AsyncThunk and Saga

In traditional Redux toolkit:
Reducers updates the store.
We dispatch tasks to update the reducr using actions.

(19) RTK Query (Redux Toolkit Query) - Full Course in Hindi by Frontend Master #redux #rtkquery #rtk - YouTube

useEffect 
In normal case it will show all default values in UI then useEffect runs then other updates run on the page like data fetching.

Without RTK-Query data is passed normally in every component.

In useEffect we make 1 extra render cyucle. So avoid it.
Other libraries for replacement of useEffect are SWR, ReactQuery, RTK Query, Tanstack.

RTK Query solves 
No API code, 
Caling API outside useEffect
Caching

There are 3 api fetch patterns 
1. Render while fetch - Uses RTK Query
2. Render then Fetch - Uses UseEffect
3. Fetch then Render - Call API before component loads outside of component that makes our code execution slow.

Reducer and slice represents module
API slice represents endpoints.

reducerPath is not needed when we have only one slice for more than 2 we need it for all.

5 different hooks are there: 

1. useQuery - it provides a hook when we cll, we get data, loadig and error state.

use + functionName + Query => useGetPostsQuery

To send payload/ header it must have method: PUT/ PATCH/ DELETE/ POST

We add apislice as middleware.

to transform data use after query: 
transformResponse: function (data) {
    return data?todos || [];
}

2. useLazyQuery - useLazyGetTodoQuery (To get manual control)
const [trigger, {data, isloading, isError}] = useLazyGetTodoQuery();

or

const [trigger, result, lastPromiseInfo (optional)] = useLazyGetTodoQuery();

Can we use multiple createApi slice in multiple files then add it to store. This is not recommended. 
Consider if required we can add our slices as 

export const store = configureStore({
    reducer: {
        [jsonPlaceholderAPI.reducerPath]: jsonPlaceholderAPI.reducer,         [jsonPlaceholderAPI.reducerPath]: deleteApiAlice.reducer,
    },
    middleware: (getDefaultMiddleware) => getDefaultMiddleware()     .concat(jsonPlaceholderAPI.middleware, deleteApiAlice.middleware)
});

To separate the features / code we use different files like

import apiSlice from "./apiSlice";

const deleteApiSlice = apiSlice.injectEndpoints({
    endpoints: (builder)= {
    return {
        deleteTodo: builder.mutation({
            query: (id) =({
            url: "todos/${id}*,
            method: "DELETE",
        }   ),
        }),
    },
    },
});

We can check our data and debugging in Redux devtools.


















setUpListners() is mandatory for onfocus, onReconnect.

unWrap normalizes the data.
In unwrap the RTKQ did is reverted. Last promise resolved is moved to previous state and returned and no 'data' key is returned in the json data. So first unwrap and refresh.

function handleAddTodo() {
    setEnteredTodo("");
    addTodo({
        completed: false,
        userId: 123,
        todo: enteredTodo,
    }).unwrap()
    .then((data) = {
        console.log(data);
        refetch();
    });
}


We can also do this by using tag Types. So there will be no need of refetch is there.
i.e. useTagtypes, provideTage and invalidateTags.

Optimistic updates:

















for optimistic updates we have onQueryStarted
that takes some data and dispatches some action 
queryFulfilled is used to catch some errors
undefined here is additional data to be sent. action.undo() undones the data changed.

Headers: Sending Custom headers
for common headers use prepareHeaders that automatically add header on each endpoint.



Prefetch:
to get data at application load
1. If component is not in the provider

2. If provider is in the component

Advanced RTK Query: Transform Response, Query Lifecycle, and Optimistic Updates | by Bashir Tobi Jaji | Medium

A Comprehensive Beginner’s Guide to RTK Query with TypeScript | by Sunil Nepali | Medium

Complete redux toolkit (Part — 4) | by Abhishek Panwar | Medium

Simplifying State Management and Data Fetching in React with Redux Toolkit Query - DEV Community

A Beginner’s Guide to Redux Toolkit Query/RTK Query | by Simranjeet Kaur | Medium

No comments:

Post a Comment

Javascript

  Let and const scope of let b in outside and inside of block value of a and b before initialization Multiple blocks Closures var and let in...