Skip to content
Youngho Chaa cha cha
TwitterHomepage

RTK Query

react, redux2 min read

RTK Query is a library built into Redux Toolkit (RTK) that provides developers with a set of tools to simplify data fetching and caching. It's an abstraction over the Redux store that automatically manages caching, re-fetching, and state updates related to remote data fetching. Before RTK Query, developers would often manually manage asynchronous actions, reducers, and state for API requests using a combination of redux-thunk or redux-saga with the base Redux Toolkit functions. RTK Query aims to reduce the boilerplate and complexity associated with this.

Here's a breakdown of RTK Query's main features and benefits:

  1. Automatic Caching: RTK Query will cache your data by default. This means that if you fetch the same data again, RTK Query will serve it from the cache rather than making a redundant API call.
  2. Automatic Re-fetching: You can configure RTK Query to automatically re-fetch data at certain intervals or when the application refocuses.
  3. Automatic State Management: RTK Query auto-generates reducers and actions for your API calls, so you don't have to write any Redux boilerplate.
  4. Optimistic Updates: It supports optimistic updates, which can provide a faster perceived loading time for users by updating the UI before the API call resolves.
  5. Polling: You can easily set up polling for endpoints that need to refresh data at regular intervals.
  6. Hooks Integration: RTK Query provides React hooks out of the box, making it easy to fetch, cache, and update data in your components.
  7. Request Lifecycle: RTK Query defines the lifecycle of a request, including actions for when a request starts, succeeds, or fails. This makes it easy to handle loading states and errors in your UI.
  8. Normalization: While not built directly into RTK Query, it's designed to work seamlessly with normalized data and integrates well with libraries like normalizr.

Basic Example:

Suppose you want to fetch a list of todos from an API. Here's how you could set it up with RTK Query:

Create an API Slice:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
export const api = createApi({
baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
endpoints: (builder) => ({
getTodos: builder.query<Array<Todo>, void>({
query: () => 'todos',
}),
}),
});
export const { useGetTodosQuery } = api;

Use the Generated Hook in a Component:

import React from 'react';
import { useGetTodosQuery } from './todosApiSlice';
const TodoList = () => {
const { data: todos, isLoading, isError } = useGetTodosQuery();
if (isLoading) return <div>Loading...</div>;
if (isError) return <div>Error loading todos</div>;
return (
<ul>
{todos?.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
);
};

In this example, by defining an endpoint in the createApi call, RTK Query auto-generates a hook (useGetTodosQuery) that we can use directly in our components to fetch data, handle loading states, and more.

© 2024 by Youngho Chaa cha cha. All rights reserved.
Theme by LekoArts