🚀 Why I Stopped Putting "Server State" in Redux If you’ve spent years building React apps, you know the struggle: your Redux store becomes a massive "junk drawer" of API data, loading booleans, and error strings. Then came TanStack Query. It changed the game by introducing a simple but powerful distinction: 𝗰𝗹𝗶𝗲𝗻𝘁 𝘀𝘁𝗮𝘁𝗲 vs. 𝘀𝗲𝗿𝘃𝗲𝗿 𝘀𝘁𝗮𝘁𝗲. 🔍 The Core Shift Most of what we store in Redux isn't actually "state"—it's a 𝗰𝗮𝗰𝗵𝗲 𝗼𝗳 𝗿𝗲𝗺𝗼𝘁𝗲 𝗱𝗮𝘁𝗮. • 𝗥𝗲𝗱𝘂𝘅/𝗭𝘂𝘀𝘁𝗮𝗻𝗱 is for things you own (Theme, Modals, Form inputs). • 𝗧𝗮𝗻𝗦𝘁𝗮𝗰𝗸 𝗤𝘂𝗲𝗿𝘆 is for things the server owns (User profiles, Product lists, Dashboard stats). 🛠️ How it manages data (without the boilerplate): 1️⃣ The Global Cache (QueryClient): Think of it as an invisible, self-managing store. You don’t write reducers; the QueryClient automatically handles the storage of every API response. 2️⃣ Query Keys = Selectors: By using a unique key like ['users', userId], any component in your app can access that data. If Component A and Component B call the same key, TanStack Query ensures only one network request is made. 3️⃣ Stale-While-Revalidate (SWR): This is the "magic." It shows users cached (stale) data immediately so the UI feels instant, then fetches the fresh data in the background. 💡 The Result? By moving server-side logic to TanStack Query, I’ve seen codebases shrink by 30-40%. No more manual useEffect for fetching, no more redundant loading variables, and no more bloated stores. Are you still using Redux for API data, or have you made the switch? Let's discuss! 👇 #ReactJS #WebDevelopment #TanStackQuery #Redux #Frontend #SoftwareEngineering #ProgrammingTips #WebDev
Ditching Redux for TanStack Query
More Relevant Posts
-
Today I learned about performance optimization and data fetching in React using Code Splitting, Lazy Loading, Suspense, and React Query (TanStack Query). ** Code Splitting Code splitting helps break large bundles into smaller chunks, so the app loads faster and only required code is loaded when needed. ** React.lazy() It allows us to load components dynamically instead of loading everything at once. const Home = React.lazy(() => import("./Home")); ** Suspense & Fallback Suspense is used with lazy loading to show a fallback UI (like a loader) while the component is loading. <Suspense fallback={<h2>Loading...</h2>}> <Home /> </Suspense> ** React Query (TanStack Query) React Query helps in fetching, caching, and managing server data efficiently. It automatically handles API caching, loading states, and background updates. @Devendra Dhote @Ritik Rajput @Mohan Mourya @Suraj Mourya #ReactJS #WebDevelopment #FullStackDeveloper #CodingJourney
To view or add a comment, sign in
-
Fetching data is easy. Handling it like a pro is the hard part. 🔄📡 In the early days of React, we all got used to the "useEffect and Fetch" pattern. But as applications grow, simple fetching isn't enough. Modern users expect zero-latency, instant feedback, and seamless synchronization. Whether I'm using Next.js Server Actions or React Query, these are the 3 principles I follow to manage data like a Senior Developer: 1️⃣ Loading States & Skeletons: Never leave your user staring at a blank screen. I use Suspense and Skeleton Screens to provide immediate visual feedback, making the app feel faster even while the data is still traveling. 2️⃣ Caching & Revalidation: Don't waste your user's data or your server's resources. Implementing smart caching (like stale-while-revalidate) ensures that your UI is updated instantly with "stale" data while the "fresh" data fetches in the background. 3️⃣ Optimistic UI Updates: Why wait for the server to say "Success" before updating a Like button or a Todo item? By using Optimistic Updates, we update the UI immediately and roll back only if the request fails. This creates a "light-speed" user experience. The best apps don't just display data—they manage the flow of data effortlessly. What’s your go-to tool for data fetching in 2026? Are you team React Query, or are you moving everything to Next.js Server Actions? Let’s debate! 👇 #ReactJS #NextJS #WebDev #DataFetching #JavaScript #FrontendArchitecture #CodingTips
To view or add a comment, sign in
-
-
🚀 Redux vs TanStack Query: Which One Should You Use in 2026? This is one of the most misunderstood topics in React development. Many developers compare Redux and TanStack Query as if they solve the same problem. They don’t. 👉 Redux manages client state 👉 TanStack Query manages server state That distinction changes everything. 🧠 Use Redux When: - You need a complex global UI state - Multiple components share local application state - You require predictable state transitions - Your app has complex workflows or business logic Examples: - Authentication state - Theme preferences - Multi-step forms - Shopping cart - Feature flags ⚡ Use TanStack Query When: - Fetching data from APIs - Caching server responses - Handling loading and error states - Synchronizing data automatically - Managing mutations and optimistic updates Examples: - User profiles - Product listings - Dashboard analytics - Comments and feeds 🔥 The Biggest Mistake Using Redux to manage API data manually. That often means writing: - Actions - Reducers - Loading states - Error handling - Cache logic With TanStack Query, most of that comes out of the box. --- 🎯 My Rule of Thumb - TanStack Query for anything that comes from the server - Redux for complex client-side state And in many modern apps, you’ll use both together. They’re not competitors. They’re complementary tools. Use the right tool for the right problem. #js #es6 #JavaScript #React #ReactRedux #TanStackQuery #WebDevelopment #Frontend #SoftwareEngineering
To view or add a comment, sign in
-
-
I made our Node.js app 30% faster using Worker Threads. No DB changes. No infra upgrades. Here's the full breakdown 👇 THE PROBLEM Our data pipeline read large files, transformed records, and wrote to MongoDB. Time taken: 8–10 minutes. Users were complaining. The instinct? Upgrade the server. The real problem? Node.js was doing everything on ONE thread. WHY NODE.JS GETS SLOW Node.js runs on a single thread — the Event Loop. Great for I/O. But CPU-heavy tasks? They BLOCK everything. This is why async/await doesn't help for CPU work — it only helps with waiting. THE FIX: WORKER THREADS Worker Threads let you run JavaScript in parallel on separate threads. The approach: → Split 50,000 records into 4 chunks → Each chunk runs in its own Worker → Use a Worker Pool to reuse threads (avoid spawning unlimited workers) → Merge results back in the main thread THE RESULTS Before: 8–10 minutes, Event Loop blocked, app unresponsive After: 2–3 minutes, Event Loop free, ~70% faster WHEN TO USE THEM ✅ Large data transformation ✅ Image/video processing ✅ Complex calculations (ML, encryption) ✅ File compression ❌ DB queries — use async/await ❌ HTTP requests — Event Loop handles these fine ❌ Simple loops — overhead isn't worth it The key insight: async/await = don't WAIT on I/O Worker Threads = don't BLOCK on CPU Most devs know the first. Few use the second — and that's where the real performance wins hide. Have you used Worker Threads in production? Drop your use case below 👇 #ImmediateJoiner #NodeJS #JavaScript #WorkerThreads #BackendDevelopment #Performance #MERNFullStackDeveloper
To view or add a comment, sign in
-
🚀 Tired of "Over-Fetching" Data? Let’s talk GraphQL! 📊 In modern React apps, fetching data efficiently is the secret to a fast UI. While REST is great, GraphQL is changing the game by letting the Frontend take control. Here is my experience using The Efficiency Blueprint: 📍Our dashboard was making 5 different API calls to show a single User Profile. 🐢 We were receiving 50 fields of data from the backend, but only using 3. This "over-fetching" made the app slow on weak networks. 🎯 I needed to simplify our data fetching and ensure the frontend only asked for exactly what it needed—no more, no less. 🛠️ I implemented GraphQL. Think of Action as Defining the Order. Instead of hitting multiple URL endpoints, I wrote a single Query. I specified the exact fields (like name and profilePic) I wanted. GraphQL acts as a smart middleman that goes to the database, picks only those items, and returns them in one neat package. 📦 ✅ We reduced network payload size by 60% and cut the number of API requests from 5 down to 1. ⚡ The result? A much faster, cleaner, and more scalable React application. 💡 Real-Life Example: The "Grocery List" 🛒 REST API: You go to the dairy aisle for milk, the bakery for bread, and the fruit section for apples. You have to visit 3 different places. 🏃♂️ GraphQL: You give a List to a personal shopper. They go to all the aisles for you and bring back a single bag with exactly those 3 items. One trip, one bag. 🛍️✅ 🏁 Conclusion GraphQL shifts the power to the Frontend.🧠✨ #ReactJS #GraphQL #WebDevelopment #FrontendDeveloper #APIDesign #SoftwareEngineering #Efficiency
To view or add a comment, sign in
-
-
The client-side data waterfall is one of the most common and most avoidable performance problems in React apps. Here's what it looks like in slow motion: 1. Browser downloads HTML 2. Browser downloads JavaScript bundle 3. React renders the shell 4. useEffect fires → fetch user profile 5. Profile arrives → render authenticated content 6. Second useEffect fires → fetch dashboard data 7. Data arrives → render the actual page Steps 4–7 are sequential network requests that happen after the page has already "loaded." On a typical connection, this adds 1–2 seconds of perceived emptiness after the spinner appears. The fix: fetch data where it's closest to the source. In Next.js App Router, server components can fetch data before sending HTML to the browser: ``` // app/dashboard/page.tsx, server component async function DashboardPage() { const [user, data] = await Promise.all([ fetchUser(), fetchDashboardData(), ]); return <Dashboard user={user} data={data} />; } ``` The client receives HTML that already contains the data. No waterfall. No spinner for server-fetched content. Where React Query + server prefetch combines the best of both: ``` // Prefetch in server component await queryClient.prefetchQuery({ queryKey: ['user'], queryFn: fetchUser }); // Client component gets it from cache instantly — no request const { data: user } = useQuery({ queryKey: ['user'], queryFn: fetchUser }); ``` The client component uses its familiar hook pattern. The data is already in the cache from the server fetch. The waterfall isn't a React problem. It's a "fetching in the wrong place" problem. What data fetching pattern has given you the biggest performance gain? #performance #frontend #fintech #web #react
To view or add a comment, sign in
-
Most React developers use data fetching libraries. Very few actually understand what’s happening under the hood. So I built something to fix that. 🚀 React Fetch Playground A visual lab to see how data fetching really works. 🔗 https://lnkd.in/gsahNcJi --- 💭 You’ve probably used things like: - caching - staleTime - background refetch - retries - optimistic updates But have you ever seen them happen? This tool makes it visible 👇 --- 🧠 What makes it different Instead of docs or theory, you get a real-time visual timeline: → request starts → data loads → cache becomes stale → background refetch kicks in All happening live. --- ⚡ Play with it like a lab - Switch between fetch / axios / custom hooks / TanStack Query - Simulate failures and retries - Control stale time and refetch intervals - Inspect cache, query state, and network behavior It’s basically DevTools for learning data fetching. --- 🔥 Why this matters (especially for senior FE roles) Understanding this deeply helps you: - avoid unnecessary re-renders - design better caching strategies - improve perceived performance - debug production issues faster This is the difference between using a library and thinking like a system designer. --- 📦 What’s next - Extracting reusable hooks as a package - Plugin system for other data libraries - More advanced visualizations (cache graphs, render impact) --- If you're preparing for frontend interviews or working on large-scale apps, this might be useful. Would love your thoughts 👇 #React #FrontendEngineering #JavaScript #WebPerformance #SystemDesign #OpenSource #TanStackQuery #DevTools
To view or add a comment, sign in
-
Last week I deployed what looked like a perfect product page. Then a client screenshot landed in my inbox… 👉 Prices from 3 days ago. The database had the correct data. The API returned the correct data. But the page? ❌ Completely frozen in time. 🚨 What was actually happening? Next.js App Router silently overrides the native fetch() API. By default, every request runs with: 👉 cache: 'force-cache' That means: Data is cached permanently Stored on disk And ignores your HTTP Cache-Control headers 🤯 The real complexity There isn’t just one cache layer — there are four: Request Memoization Data Cache Full Route Cache Router Cache 👉 Which makes debugging stale data extremely tricky 👉 Especially when everything works fine locally ✅ How to fix it properly ✔ Always define your caching strategy explicitly ✔ Use revalidate for controlled updates ✔ Call revalidatePath() or revalidateTag() after mutations ✔ Use cache: 'no-store' only for real-time or user-specific data ✔ Tag your fetches — it’s the most scalable approach 🔑 Key Takeaways Next.js fetch() defaults to permanent caching Dev mode does NOT reflect production caching behavior Stale data bugs usually appear after deployment Proper cache control = predictable apps Bookmark this. Your future self will thank you when your client sends another screenshot. 🔖 💬 What’s the worst caching bug you’ve faced in Next.js? #NextJS #WebDev #React #TypeScript #JavaScript #Frontend #FullStack #SoftwareDevelopment #Programming #TechTips
To view or add a comment, sign in
-
-
🌐 Master Server-State: TanStack React Query vs. Redux 🔍 What is TanStack React Query? TanStack Query (formerly React Query) is a Server-State library. It’s designed specifically to manage asynchronous data—fetching, caching, synchronizing, and updating state that lives on a server. 📡✨ It automates the "boring" parts of development: Automatic Caching: No more manual loading spinners on every click. 🏎️ Background Refetching: Keeps your data fresh while the user stays on the page. 🔄 Error Handling: Built-in retry logic and error states. 🛠️ ⚖️ How is it different from Redux? Redux is for Client-State: It manages data that lives only in your app (like a sidebar being open, a dark mode toggle, or a multi-step form). It is highly predictable but requires lots of "boilerplate" (actions, reducers, thunks). 🧠 TanStack Query is for Server-State: It manages data that comes from an API. It replaces 50 lines of Redux boilerplate with a single, powerful hook. ⚡ 🏥 Real-Life Example: The "Library vs. Personal Notepad" 📚 Imagine you are researching a topic: Redux (Personal Notepad): You write down every single fact yourself. If a fact changes at the source, you have to manually cross it out and rewrite it. If you lose your notepad, you have nothing. 📝 TanStack Query (The Librarian): You ask the librarian for a book. They give it to you immediately if it’s on the shelf (Caching). If it’s old, they go get a new version while you keep reading (Background Update). If the book is missing, they try again automatically (Retries). 👩🏫✅ #ReactJS #TanStackQuery #Redux #WebDevelopment #FrontendArchitecture #JavaScript #StateManagement
To view or add a comment, sign in
-
-
🚀 We stopped using Redux for server state — and built everything on TanStack Query instead. In a large Next.js 15 + React 19 app, this architecture scaled surprisingly well. Here’s what worked 👇 🏭 Query factories > raw hooks We wrapped useQuery / useInfiniteQuery into small factories. → Consistent query keys → Easy cache updates (setQueryData) → Simple invalidation No more scattered queryKey arrays across the codebase. 💾 Selective cache persistence (not everything!) Only important queries are saved to IndexedDB using a marker in the key. → No bloated cache → Fully controlled persistence ♾️ Virtual + infinite scrolling (game changer) We combined infinite queries with virtualization. 👉 The key idea: The virtualizer decides what to fetch — not the UI. This made large tables and kanban boards feel instant, even with thousands of rows. 📊 Reusable table layer Our table doesn’t care about data type. We inject a hook that returns paginated data. → Same table works for users, pipelines, or anything else → Clean separation of UI and data logic 🔄 Real-time updates without refetching WebSocket events directly update the cache using setQueryData. → UI updates instantly → No polling → One single source of truth 🔑 Simple invalidation We created a small utility with named invalidation helpers. → No one remembers query keys → Mutations stay clean 💡 Big takeaway Server state does NOT need Redux. TanStack Query already solves caching, syncing, and real-time updates — you just need to structure it well. #TanStack #ReactQuery #NextJS #React #Frontend #WebDev #JavaScript #TypeScript
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development