今日已更新 50 条资讯 | 累计 24336 条内容
关于我们

Stop Using `useEffect` for Data Fetching—Please, I Beg You

Oge Obubu 2026年07月26日 23:55 1 次阅读 来源:Dev.to

The Scene It's 2 AM. You're staring at your screen, debugging why your dashboard keeps showing yesterday's data even after you've changed the filter. Your useEffect dependency array looks like a crime scene. You've got three useState hooks just to manage loading, error, and data. You added a cleanup function, but somehow the component still throws that dreaded warning: "Can't perform a React state update on an unmounted component." You take a sip of cold coffee. You wonder where it all went wrong. The Problem with useEffect for Data Fetching Let's be honest with ourselves. useEffect was never designed for data fetching. The React team gave us this hook to synchronize with external systems, DOM events, subscriptions, and timers. But somewhere along the line, we collectively decided to use it as our go-to tool for API calls. And look, I get it. When you're learning React, the pattern is simple: useEffect (() => { const fetchData = async () => { setLoading ( true ); const response = await fetch ( ' /api/users ' ); const data = await response . json (); setUsers ( data ); setLoading ( false ); }; fetchData (); }, []); It works. Until it doesn't. Here's what happens when your application grows: Race Conditions — When your user clicks filters too quickly, old requests return after newer ones and override your state. The UI shows mismatched data, and you waste hours adding request cancellation logic that nobody on your team fully understands. Unnecessary Re-renders — Every state update triggers a re-render. With useEffect , you're juggling at least three states: data , loading , and error . Three states, three renders, even before React mounts your actual content. Poor Caching — If a user visits a page, leaves, and comes back, your useEffect fires again. Same data, same API call, same network cost. Multiply this by a thousand users, and you're burning your backend for no good reason. Manual Cleanup Headaches — Need to cancel pending requests? Need to prevent state updates

本文内容来源于互联网,版权归原作者所有
查看原文