TanStackT
TanStackโ€ข2y agoโ€ข
1 reply
endless-jade

Passing initialData / placeholderData from the server

In the docs, the suggested way to use React-Query on Nextjs App router is by dehydrating and hydrating the query.

For me, that's a bit too much (I am a newbie โœŒ๐Ÿป - still working of my mental model of...well everything) and I tried a different approach and it seems to work fine.

I just need to know if my approach is ok too, even if it's not the best. This is how I am doing it:

In page.tsx (server component) I get the data ๐Ÿ‘‡๐Ÿป

export default async function Page({
    params,
    searchParams,
}: {
    params: { slug: string };
    searchParams: { [key: string]: string | string[] | undefined };
}) {
    const serverPosts = await postGetManyAction({
        skip: 0,
        take: 5,
    });
// ...


And pass to the component that needs it, and use it when calling my custom hook, where I use it like this:

const postGetManyActionOptions = ({
    skip,
    take,
}: {
    take: number;
    skip: number;
}) => {
    return {
        queryKey: ['PaginatedClient', { take }, { skip }],
        queryFn: () => postGetManyAction({ take, skip }),
        staleTime: 10 * 1000,
    };
};

export const usePostGetManyQuery = ({
    initialData,
    take,
    skip,
}: {
    initialData: Awaited<TFetchResponse<TPost>>;
    take: number;
    skip: number;
}) => {

//...

return useQuery({
        ...postGetManyActionOptions({ take, skip }),
        placeholderData: (previousData) =>
            previousData ? previousData : initialData,
    });
Was this page helpful?