atharva Profile picture
21 • i build, ship, sleep • 🕉️

Aug 2, 12 tweets

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 🧵

(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.

(4/n) Layout.tsx:

>now we will use that provider in our Layout.

(5/n) Actual part starts here:

>created a getTodos function to fetch Todos from server.

(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.

(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.

(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.

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 :)

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling