I stopped using useEffect for data fetching. Here's why. For years, my React components looked like this: useEffect(() => { setLoading(true); fetch('/api/users') .then(res => res.json()) .then(data => setUsers(data)) .catch(err => setError(err)) .finally(() => setLoading(false)); }, []); Loading state. Error state. Race conditions. Cleanup functions. Stale closures. Every. Single. Component. Then I switched to React Query (TanStack Query) and deleted 40% of my state management code overnight. Here's what changed: → No more loading/error/data useState triplets → Automatic caching — same data across 10 components, 1 network request → Background refetching — users always see fresh data without spinners → Race condition handling — built in, not bolted on → Retry logic — automatic, configurable, zero custom code But here's what most tutorials won't tell you: React Query doesn't replace ALL useEffect calls. It replaces the ones you should never have written in the first place. useEffect is still perfect for: • Subscriptions (WebSocket, event listeners) • DOM synchronization • Third-party library integration The mistake is using useEffect as a "fetch on mount" hook. That was always a workaround, not a pattern. In my TypeScript projects, I enforce this with a simple ESLint rule: no fetch() inside useEffect. If you're fetching data, use a query hook. Period. The result? Components that are 50% shorter, easier to test, and actually work correctly with React 18+ concurrent features. What's your go-to data fetching approach in React? Still useEffect, or have you moved on? #React #TypeScript #ReactQuery #TanStackQuery #WebDevelopment #JavaScript #DeveloperProductivity #CleanCode
Alex Rogov’s Post
More Relevant Posts
-
🚀 Day 15/30 – Lifting State Up (Deep Dive) Struggling to sync data between components? 🤔 Today I learned one of the most important React concepts ⚡ 👉 Lifting State Up Today I learned: ✅ Move state to the closest common parent ✅ Share data via props ✅ Maintain single source of truth 💻 Real Example: function Parent() { const [name, setName] = useState(""); return ( <> </> ); } function ChildInput({ name, setName }) { return ( <input value={name} onChange={(e) => setName(e.target.value)} /> ); } function ChildDisplay({ name }) { return Hello {name}; } 🔥 What actually happens: 1️⃣ User types in ChildInput 2️⃣ setName updates parent state 3️⃣ Parent re-renders 4️⃣ ChildDisplay gets updated value 👉 Both components stay perfectly in sync 💡 Wrong Approach (Common Mistake): ❌ Separate state in each component function ChildA() { const [name, setName] = useState(""); } function ChildB() { const [name, setName] = useState(""); } 👉 This creates inconsistent UI 😵 ⚡ Real Use Cases: Shared form data Cart state across components Filters + product list sync ⚡ Advanced Insight: React enforces one-way data flow 👉 Parent → Child (via props) 🔥 Key Takeaway: If multiple components depend on same data → lift it up. Are you still duplicating state or managing it correctly? 👇 #React #StateManagement #FrontendDevelopment #JavaScript #WebDevelopment
To view or add a comment, sign in
-
-
I ditched useEffect for data fetching. Here's why I'm not going back. For the longest time, I thought useEffect was the "React way" to fetch data. Loading state? Add a useState. Error handling? Another useState. Race conditions? Then I discovered React Query — and I felt like I'd been writing in hard mode the whole time. Look at the difference: ❌ Before — 15+ lines just to fetch a user. Manual cleanup. Race condition workarounds. Error & loading states all over the place. ✅ After — useQuery. Three lines. Done. Here's what I gained immediately: ⚡ Automatic caching & deduplication — two components needing the same data? One network call. Not two. 🔁 Background refetching — data stays fresh without me writing a single timer or polling loop. 🛡️ Race conditions — handled — no more "old response overwriting new one" bugs. React Query deals with it out of the box. 📉 ~60% less boilerplate — I removed hundreds of lines of state management code across our dashboard in one refactor. The mental shift that helped me: useEffect is for syncing with external systems. It was never meant to be a data fetching tool. React Query is purpose-built for server state — and it shows. If you're still reaching for useEffect every time you need an API call, give React Query one week. You won't look back. What was your turning point with server-state management? Drop it below 👇 #ReactQuery #ReactJS #WebDev #Frontend #JavaScript #SoftwareEngineering
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
-
-
React Query?? Fetching data with React is generally a process that involves a lot of code. You often need to use the “useEffect” hook in combination with “useState” to manage the fetched data. This requires a lot of boilerplate that we have to write in every component in which we want to fetch data. Become a Medium member React Query can help you cut down on the code you write when making network requests with React. All of this React code that we had to write before can be replaced with the hook “useQuery”. From it we get back all of the data that we need without having to declare a state variable: However, making data fetching easier only covers a small slice of what React Query does. What makes it a very powerful library is that it caches (saves) requests that we make. So in many cases if we’ve requested data before, we don’t have to make another request, we can just read it from the cache. This is immensely helpful because it cuts down repetition in our code, reduces the load we put on our API, and helps us manage our overall app state. If you pick any library to start adding to your projects today out of this list, make it React Query. #reactjs #javascript #useEffect #useQuery #nextjs
To view or add a comment, sign in
-
-
React Query?? Fetching data with React is generally a process that involves a lot of code. You often need to use the “useEffect” hook in combination with “useState” to manage the fetched data. This requires a lot of boilerplate that we have to write in every component in which we want to fetch data. Become a Medium member React Query can help you cut down on the code you write when making network requests with React. All of this React code that we had to write before can be replaced with the hook “useQuery”. From it we get back all of the data that we need without having to declare a state variable: However, making data fetching easier only covers a small slice of what React Query does. What makes it a very powerful library is that it caches (saves) requests that we make. So in many cases if we’ve requested data before, we don’t have to make another request, we can just read it from the cache. This is immensely helpful because it cuts down repetition in our code, reduces the load we put on our API, and helps us manage our overall app state. If you pick any library to start adding to your projects today out of this list, make it React Query. #reactjs #javascript #useEffect #useQuery #nextjs
To view or add a comment, sign in
-
-
React Query?? Fetching data with React is generally a process that involves a lot of code. You often need to use the “useEffect” hook in combination with “useState” to manage the fetched data. This requires a lot of boilerplate that we have to write in every component in which we want to fetch data. Become a Medium member React Query can help you cut down on the code you write when making network requests with React. All of this React code that we had to write before can be replaced with the hook “useQuery”. From it we get back all of the data that we need without having to declare a state variable: However, making data fetching easier only covers a small slice of what React Query does. What makes it a very powerful library is that it caches (saves) requests that we make. So in many cases if we’ve requested data before, we don’t have to make another request, we can just read it from the cache. This is immensely helpful because it cuts down repetition in our code, reduces the load we put on our API, and helps us manage our overall app state. If you pick any library to start adding to your projects today out of this list, make it React Query. #reactjs #javascript #useEffect #useQuery #nextjs
To view or add a comment, sign in
-
-
📘 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐌𝐨𝐝𝐮𝐥𝐞 (𝐁𝐚𝐬𝐢𝐜) 𝐒𝐞𝐜𝐭𝐢𝐨𝐧 2: 𝐕𝐚𝐫𝐢𝐚𝐛𝐥𝐞𝐬 1.What is a variable? 2.Why do we use a variable? 3.How to declare a variable? 4.Tell me about variable declaration rules? 5.How many types of variables do you know? 6.When do we use var? 7.When do we use let? 8.When do we use const? 9.How to create an undefined variable? 10.What is an undefined variable? 11.What is undefined? 12.What is NaN? 13.What is null? 14.What is concatenation? 15.What is Infinity? 16.How to assign data to a variable / How to assign a variable data? 17.Variable is primitive or non-primitive? 🎯 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧𝐬 (𝐄𝐱𝐭𝐫𝐚) 1.Difference between var, let, and const? 2.What is variable hoisting? 3.Why can var be accessed before declaring it? 4.What is temporal dead zone (TDZ)? 5.Can we reassign const variable? 6.Why shouldn't modern JavaScript use var? 𝐒𝐞𝐜𝐭𝐢𝐨𝐧 3: 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐃𝐚𝐭𝐚 𝐓𝐲𝐩𝐞𝐬 & 𝐊𝐞𝐲𝐰𝐨𝐫𝐝𝐬 1.JavaScript data types? 2.What is a reserved keyword? 3.What is a special keyword? 4.How can check type data type? 5.JavaScript variables is case-sensitive? 6.JavaScript variable naming conventions? 7.How to convert string ("20") to number (20)? 8.JavaScript built-in functions? 🎯 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧𝐬 (𝐄𝐱𝐭𝐫𝐚) 1.Difference between primitive and reference types? 2.What is type coercion? 3.Difference between null and undefined? 4.What is typeof null / What is the output of typeof null and why? (Important trick question) 5.What is the difference in memory management between primitive and reference type data? #DotNet #AspNetCore #MVC #FullStack #SoftwareEngineering #ProgrammingTips #DeveloperLife #LearnToCode #JavaScript #JS #JavaScriptTips #JSLearning #FrontendDevelopment #WebDevelopment #CodingTips #CodeManagement #DevTools
To view or add a comment, sign in
-
-
🚀 Stop Managing API State Manually in React! If you're still using `useEffect` + `useState` for API calls… you're doing extra work 😅 Let’s talk about React Query (TanStack Query) 👇 --- 🧠 What is React Query? A powerful library to **fetch, cache, and manage server state (API data)** in React apps. --- ❌ Traditional Way (Problem) * Manual loading & error handling * Repeated API calls * No caching * Complex & messy code --- ✅ With React Query (Solution) * Automatic caching ⚡ * Background refetching 🔄 * Shared data across components 🔗 * Cleaner code 🧹 * Better performance 🚀 --- ⚙️ How it works? 1️⃣ Fetch data 2️⃣ Store in cache 3️⃣ Return instantly on next request 4️⃣ Refetch in background if stale 5️⃣ UI updates automatically --- 🔥 Key Benefits ✔️ Auto caching (no duplicate API calls) ✔️ Faster performance ✔️ Less boilerplate code ✔️ Built-in mutation support (POST/PUT/DELETE) ✔️ Smart retry & error handling ✔️ Data sync across components --- ⚠️ Disadvantages * Learning curve (staleTime, cacheTime) * Not needed for small apps * Slight increase in bundle size --- 🧩 When to Use React Query? ✅ API-heavy applications ✅ Dashboards / Admin panels ✅ Shared data across components ✅ Need performance optimization --- 🚫 When NOT to Use? ❌ Static or simple apps ❌ No backend/API usage ❌ Minimal state management #ReactJS #WebDevelopment #Frontend #JavaScript #ReactQuery #TanStackQuery #SoftwareDevelopment
To view or add a comment, sign in
-
-
Slow React vs Fast React — 2.5s to 0.2s Same component. Same data. 2.5 second render time vs 0.2 seconds. The difference is three React optimization patterns most developers skip. -> The slow version Re-fetches data on every single render. No dependency array control on useEffect. No memoization anywhere. The heavy child component re-renders every time the parent updates even when nothing it depends on has changed. The UI thread gets blocked during computation. Result: 2.5 second render. Users wait. Users leave. -> The fast version — three changes First: fetch once on mount. Add an isMounted flag to your useEffect and an empty dependency array. The data fetches once when the component mounts, not on every render. A cleanup function prevents state updates on unmounted components which eliminates memory leak warnings. Second: useMemo for expensive calculations. Wrap any computation that processes large datasets in useMemo with the correct dependencies. The calculation only runs when the data it depends on actually changes — not on every render. const processedData = useMemo(() => data?.map(item => ({...item, result: heavyCalculation(item.value)})), [data] ); Third: React.memo prevents unnecessary child re-renders. Wrap the component in React.memo and it only re-renders when its props actually change. If the parent re-renders for unrelated reasons, the child stays untouched. Result: 0.2 second render. 92 percent faster. Same functionality. These three patterns — controlled useEffect, useMemo, and React.memo — are not advanced React. They are standard React. But most components in production codebases are missing at least one of them. Performance is not something you add at the end. It is something you build correctly from the start. What React performance optimization made the biggest difference in a project you worked on? #React #Performance #JavaScript #FrontendDevelopment #WebDevelopment #Developers #ReactHooks
To view or add a comment, sign in
-
-
Day 93 of me reading random and basic but important dev topicsss.... Today I read about the POST Requests, Binary Data & Performance in fetch() 1. Headers: Reading and Writing * Reading: response.headers gives you a Map-like object. You can easily get specific headers via response.headers.get('Content-Type') or iterate over all of them using a for...of loop. * Writing: Pass a headers object in the options parameter. Note: The browser exclusively controls certain "forbidden" headers (like Host, Origin, Referer, and Cookie) for security reasons. 2. Making POST Requests To send data, you need to add method and body to your fetch options. When sending a JSON payload, don't forget your Content-Type! By default, sending a string body sets the content type to text/plain. let user = { name: 'John', surname: 'Smith' }; let response = await fetch('/api/user', { method: 'POST', headers: { 'Content-Type': 'application/json;charset=utf-8' }, body: JSON.stringify(user) }); 3. Submitting Binary Data (Images/Files) Fetch handles binary data beautifully. You can pass a Blob or BufferSource directly to the body. If you pass a Blob (for instance, an image generated from an HTML <canvas> using canvas.toBlob), you don't even need to set the Content-Type header manually! The Blob object's built-in type (e.g., image/png) automatically becomes the Content-Type. 4. Pro-Tip: Optimizing Concurrent Fetches When fetching multiple independent endpoints, never map an array of URLs to an array of fetch() calls and then blindly await Promise.all(...) before calling .json(). Why? It forces the JSON parsing to wait for the slowest network request to finish! Instead, attach .then(res => res.json()) directly to each individual fetch promise. This ensures that as soon as any single request finishes, it immediately starts processing its JSON payload without waiting for its siblings. Keep Learning!!!! #JavaScript #WebDevelopment #SoftwareEngineering #WebPerformance #FetchAPI
To view or add a comment, sign in
-
More from this author
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
This post came on my timeline and I'm like wow The background refetching is a game changer, no need for spinners that feel like something is coming Promise.all is abstracted Lifted state to Global is accomplished This are effect of realll solutions to real problems But then for little projects that need Global state , you might consider useEffect and context API, at least solves the issue of "fetch on mount" hook