🚀 Server-Side Sorting in React with React Query & Chakra UI
Most of the Frontend developers directly jump into the native sort function given by Javascript when it comes to sorting:
const sortedProducts = [...products].sort((a, b) => a.price - b.price);
This works great for small datasets.
But what happens when your API returns 50,000+ products?
Every user must download every product before React can sort them. That results in:
- ❌ Large API responses
- ❌ Slow page loads
- ❌ High memory usage
- ❌ Poor scalability
A better solution is server-side sorting.
Instead of sorting in React, send the sorting options to your backend using query parameters and let your database return the data already sorted.
Why Server-Side Sorting?
❌ Frontend Sorting
GET /products
↓
Returns 50,000 Products
↓
React Sorts Everything
Problems
- Large API responses
- Slow loading
- High memory usage
- Doesn't scale
- More work for the browser
✅ Server-Side Sorting
GET /products?sortBy=price&order=asc
↓
Backend sorts database
↓
Returns sorted products
Benefits
- Faster responses
- Smaller payloads
- Database does the heavy lifting
- Better scalability
- Cleaner frontend
Step 1 — Install Dependencies
npm install @tanstack/react-query axios
Step 2 — Create API Function
import axios from "axios";
export const getProducts = async (sortBy, order) => {
const response = await axios.get("/products", {
params: {
sortBy,
order,
},
});
return response.data;
};
Example request:
GET /products?sortBy=price&order=desc
Step 3 — Create React Query Hook
import { useQuery } from "@tanstack/react-query";
export const useProducts = (sortBy, order) => {
return useQuery({
queryKey: ["products", sortBy, order],
queryFn: () => getProducts(sortBy, order),
});
};
Each sorting combination gets its own cache automatically.
Step 4 — Create the Sort Dropdown
<Select
value={sort}
onChange={(e) => setSort(e.target.value)}
>
<option value="latest">Latest</option>
<option value="price-asc">Price: Low to High</option>
<option value="price-desc">Price: High to Low</option>
<option value="name-asc">Name (A-Z)</option>
<option value="name-desc">Name (Z-A)</option>
</Select>
Step 5 — Convert the Selected Option
const sortOptions = {
latest: {
sortBy: "createdAt",
order: "desc",
},
"price-asc": {
sortBy: "price",
order: "asc",
},
"price-desc": {
sortBy: "price",
order: "desc",
},
"name-asc": {
sortBy: "title",
order: "asc",
},
"name-desc": {
sortBy: "title",
order: "desc",
},
};
const { sortBy, order } = sortOptions[sort];
Step 6 — Fetch Sorted Products
const { data, isLoading } = useProducts(sortBy, order);
Flow:
User Selects Sort
↓
React State Updates
↓
React Query detects new queryKey
↓
API Request
↓
Backend Sorts Database
↓
Updated Products
Step 7 — Render Products
{data?.products?.map((product) => (
<ProductCard
key={product.id}
product={product}
/>
))}
React Query automatically handles:
- Loading state
- Error state
- Request caching
- Background refetching
Bonus — Combine Search + Sorting
GET /products?search=iphone&sortBy=price&order=asc
useQuery({
queryKey: ["products", search, sortBy, order],
queryFn: () =>
getProducts({
search,
sortBy,
order,
}),
});
Every search and sorting combination is cached independently.
Complete Flow
User Selects Sort
↓
Chakra UI Select
↓
React State
↓
React Query
↓
GET /products?sortBy=price&order=asc
↓
Backend Database
↓
Sorted Products
↓
React UI Updates
Final Thoughts
Frontend sorting is perfectly fine for small datasets.
However, for production applications such as:
- Ecommerce
- CRM Systems
- Admin Dashboards
- Inventory Management
- SaaS Platforms
Server-side sorting is the preferred approach because it minimizes data transfer, improves performance, and keeps your frontend lightweight.
Combined with TanStack React Query and Chakra UI, you can build scalable, production-ready React applications with very little code.
🎥 Watch the Full Ecommerce Series
This tutorial is part of my Modern Ecommerce in React & Modern Stacks (2026) series.
📺 Full Playlist
https://www.youtube.com/watch?v=Jluy-W9eP-4&list=PL_02r0p8Ku_6tR8L-n-yj7MW8rrMtswwk
🎬 This Episode
https://www.youtube.com/watch?v=NUGWQuFeNN8&list=PL_02r0p8Ku_6tR8L-n-yj7MW8rrMtswwk&index=12
If you enjoy practical React tutorials covering React Query, Chakra UI, Zustand, Stripe, Firebase, Authentication, and Full-Stack Development, consider following Codeek for more production-ready React content.
Top comments (0)