TanStack Query in Next 15 and React 19?
Unanswered
Champagne D’Argent posted this in #help-forum
Champagne D’ArgentOP
I am not sure if I am using the
I have this api function:
And this hook
I am fetching the data like this in my component
Is that correct?
use
hook correct here with TanStackQuery in React 19, can someone double check?I have this api function:
export async function getPost(id: number): Promise<Post> {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`)
if (!response.ok) {
throw new Error('Network response was not ok')
}
return response.json()
}
And this hook
"use client";
import { useQuery } from "@tanstack/react-query";
import { getTestData } from "@/lib/api";
export function usePost(id: number) {
return useQuery({
queryKey: ["post", id],
queryFn: () => getPost(id),
});
}
I am fetching the data like this in my component
interface PostPageProps {
params: Promise<{ id: string }>;
}
export default function PostPage(props: PostPageProps) {
const { params } = props;
const { id } = use(params);
const { data: post, isLoading, error } = usePost(Number(id));
Is that correct?
3 Replies
Champagne D’ArgentOP
The Next 15 Documentation says following:
Client Components
There are two ways to fetch data in Client Components, using:
1. React's use hook
2. A community library like SWR or React Query
Right now I am using both, that confuses me
Client Components
There are two ways to fetch data in Client Components, using:
1. React's use hook
2. A community library like SWR or React Query
Right now I am using both, that confuses me
Asian black bear
You have to ask yourself whether you want/need client-side fetching in the first place. In most it's not necessary and you can just fetch server-side.
If you want client-side fetching and have good reasons for it then you should look into prefetching and initializing the fetched queries otherwise you're ignoring the benefits of SSR with Next.js.