Using React Router with React Query
So far, we have experienced the benefits of both React Router and React Query data fetching. React Router reduces the number of re-renders, while React Query provides a client-side cache of the data. In this section, we will use these libraries together in our app so that it has both these benefits.
Carry out the following steps:
- Start by opening
App.tsx
and change the loader function on the route definition to the following:const router = createBrowserRouter([
{
path: '/',
element: ...,
loader: async () => {
const existingData = queryClient.getQueryData([
'postsData',
]);
if (existingData) {
return defer({ posts: existingData });
...