atharva Profile picture
Aug 2 12 tweets 4 min read Read on X
last night, I was skimming TanStack Query docs and went down a rabbit hole on its server-side usage with Next.js. What I found is a total gamechanger for performance. @tan_stack 🤯

>it's a pattern that combines server-side prefetching with client-side hydration to practically eliminate initial page load spinners. When you pair it with Server Actions for mutations, your app feels insanely fast.

here's how it works, a Thread 🧵Image
(1/n) Comparison:

>the old way (Client-Side Fetching):
You go to a restaurant and sit down. Only then do you call the waiter, place your order, and wait for the kitchen to cook and bring you your food. That "waiting for your food" part is the loading spinner your user sees.

>the new way (This Pattern):
You pre-order your meal online. When you arrive at the restaurant, the food is already on your table, hot and ready to eat. No waiting! This is what we're giving our user an instant experience.

will elaborate below.
(2/n) why old way is slow and bad? let's see

>in the traditional client-side fetching model, the data fetching process creates a noticeable delay for the user.

>when a user requests a page, the server initially sends a minimal HTML structure and the required JavaScript. The browser renders this data-less page, forcing the user to see a loading state.

>only after this initial page is loaded does the client-side code execute.
A useEffect hook then triggers a second network request to an API endpoint to fetch the necessary data. The server processes this request and sends the data back. Once the browser receives the data, the component updates its state, triggering a re-render to finally display the content. This multi-step process, where data fetching starts only after the page is already on the client, is the direct cause of the perceived delay and loading indicators.
(3/n) Setup of Tanstack Query in NextJS:

install tanstack: npm install @tanstack/react-query

>here we created a provider component. This is a Client Component that will wrap your application layout.Image
(4/n) Layout.tsx:

>now we will use that provider in our Layout.Image
(5/n) Actual part starts here:

>created a getTodos function to fetch Todos from server.Image
(6/n)

>first, the server gets the data before it even sends the page to the user. This happens in a Server Component (app/todos/page.tsx), which runs exclusively on the server.

>at this point, your page loads with the todos displayed instantly, without a client-side loading spinner.

we use queryClient.prefetchQuery to fetch the data.Image
(7/n) Actions:

>this code defines a Next.js Server Action that securely handles creating a new todo on the server. When called from a client-side form, it saves the data and then uses revalidatePath to clear the server's cache for the /todos page, ensuring all users see the updated list.Image
(n/n) Final Code:

>this is a game-changer compared to the old way. We used to have to manually manage everything. We'd have multiple useState calls for loading, errors, and submission states. Then, after a successful fetch, we'd have to figure out how to either trigger another fetch for the whole list or try to manually add the new item to our local state, which can get complicated fast.

>this new approach is just so much cleaner because you're just stating your goal. You say,
"When this form is submitted, run this server logic, and when it's done, make sure this data is fresh."
All the messy steps in between are handled for you.

>you can give it a try using this and make a boilerplate to test using actual backend apis, caching and database, lmk if you do so, would love to see.Image
that's all i found while diving in docs and had a thought that i will explain this to y'all,
if you found this helpful please do lemme know what more doubts you have or any other threads you want.

for more such new threads and learnings please do follow me @AtharvaXDevs and do share, like, repost.

thankss sayonara!!
tagging for reach and suggestions :
@akshad_999 @ramxcodes @icantcodefyi @shydev69 @Abhinavstwt @soham_btw @pankajkumar_dev @mihirtwt
suggestions: @Hiteshdotcom @kirat_tw :)

• • •

Missing some Tweet in this thread? You can try to force a refresh
 

Keep Current with atharva

atharva Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Don't want to be a Premium member but still want to support us?

Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal

Or Donate anonymously using crypto!

Ethereum

0xfe58350B80634f60Fa6Dc149a72b4DFbc17D341E copy

Bitcoin

3ATGMxNzCUFzxpMCHL5sWSt4DVtS8UqXpi copy

Thank you for your support!

Follow Us!

:(