Post Links
RTK Query: reactTutorial: RTK Query
Webpack: reactTutorial: October 2025
Hooks: reactTutorial: September 2025
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
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...