惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

美团技术团队
P
Privacy International News Feed
P
Proofpoint News Feed
Security Archives - TechRepublic
Security Archives - TechRepublic
C
CXSECURITY Database RSS Feed - CXSecurity.com
Know Your Adversary
Know Your Adversary
Security Latest
Security Latest
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Attack and Defense Labs
Attack and Defense Labs
NISL@THU
NISL@THU
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
GbyAI
GbyAI
N
News and Events Feed by Topic
N
News | PayPal Newsroom
Y
Y Combinator Blog
C
CERT Recently Published Vulnerability Notes
N
Netflix TechBlog - Medium
S
Security Affairs
Spread Privacy
Spread Privacy
罗磊的独立博客
腾讯CDC
MyScale Blog
MyScale Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
L
LINUX DO - 热门话题
The Cloudflare Blog
L
LangChain Blog
博客园_首页
H
Hacker News: Front Page
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
博客园 - 聂微东
SecWiki News
SecWiki News
A
Arctic Wolf
爱范儿
爱范儿
Google Online Security Blog
Google Online Security Blog
T
Threat Research - Cisco Blogs
Hacker News - Newest:
Hacker News - Newest: "LLM"
有赞技术团队
有赞技术团队
The GitHub Blog
The GitHub Blog
Cyberwarzone
Cyberwarzone
博客园 - 叶小钗
V
Visual Studio Blog
V
V2EX
T
Tailwind CSS Blog
Project Zero
Project Zero
T
The Blog of Author Tim Ferriss
F
Fortinet All Blogs
MongoDB | Blog
MongoDB | Blog
D
Docker

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Why I Stopped Using useEffect to Sync State — and What I Use Instead
Juan Torchia · 2026-05-21 · via DEV Community

Why I Stopped Using useEffect to Sync State — and What I Use Instead

I made a mistake that, I suspect, most teams working with React are still making today: I used useEffect as a general-purpose state synchronization tool. If something changed and I wanted to react to it, there was the effect. Clean, familiar, and — I figured this out way too late — completely wrong for most of those cases.

I'm not telling you this to flagellate myself. I'm telling you because when I systematically audited the effects in a React 19 codebase, I found exactly four categories of misuse repeated over and over. Each one has a better solution. And none of the four requires hacks or external libraries.

My thesis: useEffect isn't broken. What's broken is the mental model we teach alongside it — as if it were the natural place to "do things when something changes." React 19 puts better tools closer to the surface, but you still need the judgment to choose between them. Without that, React 19 just gives you new places to put the same old problems.


useEffect for state synchronization: the antipattern nobody names

The official React documentation has an entire page called "You Might Not Need an Effect" that anyone should read before writing their first effect. It's not an opinionated blog post — it's official documentation from the React team. And it says explicitly that using effects to transform data during render is wrong.

The core problem is that useEffect runs after the render. When you use it to derive or sync state from props or existing state, you're forcing an extra cycle: render → effect → setState → render again. That's visual noise, momentary inconsistencies, and a dependency graph that becomes impossible to follow.

Look at this classic pattern I found repeated everywhere:

// ❌ useEffect to derive state — documented antipattern by React
const [items, setItems] = useState<Item[]>([]);
const [filteredItems, setFilteredItems] = useState<Item[]>([]);

useEffect(() => {
  // Every time items changes, we filter
  // This generates an unnecessary extra render
  setFilteredItems(items.filter(item => item.active));
}, [items]);

Enter fullscreen mode Exit fullscreen mode

This effect looks reasonable. It isn't. It generates two renders when one is enough. And if items comes from an async fetch, the intermediate state where filteredItems is stale is completely visible to the user.

The solution is to not have filteredItems as state at all:

// ✅ Derived state — calculated during render, no effect needed
const [items, setItems] = useState<Item[]>([]);

// Recalculated on every render that involves items
// If the calculation is expensive, useMemo is the tool — not useEffect
const filteredItems = items.filter(item => item.active);

Enter fullscreen mode Exit fullscreen mode

If the filter is computationally expensive, useMemo with the right dependency. If it's cheap — and most are — not even that. Just a direct calculation during render.


The 4 concrete categories and what replaces them

1. State derived from props or existing state → calculation in render or useMemo

We already saw this above. The practical rule: if you can calculate something from the state or props you already have, it's not new state. It's a function of what already exists.

// ❌ Version with effect
const [user, setUser] = useState<User | null>(null);
const [displayName, setDisplayName] = useState('');

useEffect(() => {
  setDisplayName(user ? `${user.firstName} ${user.lastName}` : 'Guest');
}, [user]);

// ✅ Correct version: derived inline
const displayName = user ? `${user.firstName} ${user.lastName}` : 'Guest';

Enter fullscreen mode Exit fullscreen mode

Looks trivial. In a real codebase with 30 components doing this, the cumulative impact on re-renders is anything but trivial.

2. Post-event synchronization → direct event handlers

Another pattern I kept finding: an effect that watches a piece of state to "do something when it changes," but that change always comes from a user interaction.

// ❌ useEffect reacting to a change that only ever comes from a click
const [selectedId, setSelectedId] = useState<string | null>(null);

useEffect(() => {
  if (selectedId) {
    analytics.track('item_selected', { id: selectedId });
    loadDetails(selectedId);
  }
}, [selectedId]);

// ✅ The event handler already knows everything it needs to know
const handleSelect = (id: string) => {
  setSelectedId(id);
  // The logic that reacts to the event goes HERE, not in an effect
  analytics.track('item_selected', { id });
  loadDetails(id);
};

Enter fullscreen mode Exit fullscreen mode

The difference isn't just aesthetic. With the effect, any change to selectedId — even a programmatic one, even from another effect — triggers the logic. With the handler, the intent is explicit: this happens when the user selects something. Fewer surprises, more control.

The React docs put it plainly: if something happens because the user did something, it goes in the event handler. If something happens because the component was shown, it goes in an effect. The confusion between these two cases is the root of most useEffect bugs I see.

3. Data fetching → use() with Suspense in React 19, or Server Components

This is the category where React 19 changes the game the most. Fetching with useEffect is the most copy-pasted pattern on the internet and one of the most problematic:

// ❌ The classic useEffect fetch — race conditions waiting to happen
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);

useEffect(() => {
  // Without cleanup, this can set state on an unmounted component
  fetch(`/api/items/${id}`)
    .then(r => r.json())
    .then(setData)
    .finally(() => setLoading(false));
}, [id]);

Enter fullscreen mode Exit fullscreen mode

This code has a classic race condition: if id changes quickly, two fetches run in parallel and the result can arrive in any order. You can mitigate it with cleanup, but that's boilerplate most people skip.

React 19 brings use() which integrates with Suspense:

// ✅ React 19: use() + Suspense — no useEffect, no manual loading state
import { use, Suspense } from 'react';

// The promise is created outside the component or passed as a prop
function ItemDetail({ itemPromise }: { itemPromise: Promise<Item> }) {
  // use() suspends the component until the promise resolves
  const item = use(itemPromise);

  return <div>{item.name}</div>;
}

// In the parent component:
function Page({ id }: { id: string }) {
  // The promise is created here, React manages the lifecycle
  const itemPromise = fetchItem(id); // function that returns Promise<Item>

  return (
    <Suspense fallback={<Skeleton />}>
      <ItemDetail itemPromise={itemPromise} />
    </Suspense>
  );
}

Enter fullscreen mode Exit fullscreen mode

But if you're working with App Router in Next.js 16, the most honest answer is: use Server Components for the fetch. The data arrives serialized to the client, no loading state, no race conditions, no useEffect. For more complex cases where the fetch depends on user interaction, use() with Suspense is the way.

This connects to something I documented in the post about Prisma Server Actions in Next.js 16 — the boundary between what runs on the server and what runs on the client significantly shifts which patterns actually make sense.

4. Post-submit transformations → Server Actions

The last category: the effect that listens to the result of a submit to update derived state, show messages, or redirect.

// ❌ useEffect watching the result of a submit
const [submitResult, setSubmitResult] = useState<Result | null>(null);
const [errorMessage, setErrorMessage] = useState('');

useEffect(() => {
  if (submitResult?.error) {
    setErrorMessage(submitResult.error.message);
  }
}, [submitResult]);

Enter fullscreen mode Exit fullscreen mode

With Server Actions in React 19 and the useActionState hook (previously useFormState), this collapses into a much more direct pattern:

// ✅ useActionState — form state and action result, integrated
import { useActionState } from 'react';

async function submitForm(prevState: State, formData: FormData): Promise<State> {
  'use server';
  // The action runs on the server, returns the new state
  const result = await processForm(formData);
  if (!result.ok) {
    return { error: result.message };
  }
  return { success: true };
}

function MyForm() {
  const [state, action, isPending] = useActionState(submitForm, { error: null });

  return (
    <form action={action}>
      {/* No useEffect, no extra state, no manual synchronization */}
      {state.error && <p className="error">{state.error}</p>}
      <button disabled={isPending}>Save</button>
    </form>
  );
}

Enter fullscreen mode Exit fullscreen mode

Form state, error feedback, and loading are all integrated without a single useEffect. It's not magic — it's that the responsibility is in the right place.


The errors that persist and the ones that disappear

There are cases where useEffect is the right tool: subscriptions to external stores, synchronization with DOM APIs you don't control (a third-party map, a canvas library), or setup/teardown of resources that exist outside of React's model.

What disappears with these patterns:

  • Race conditions in fetchuse() and Server Components eliminate them structurally
  • Inconsistent intermediate renders — derived state has no inconsistent state because it isn't state
  • Chained effect graphs — when one effect sets state that fires another effect, debugging is hell. Event handlers cut that off at the root
  • Forgotten cleanup — if there's no effect, there's no cleanup to forget

What doesn't disappear:

  • Thinking about dependenciesuseMemo also has a dependency array. use() requires understanding how React handles promises. The judgment is still necessary.
  • Suspense complexity — badly placed boundaries break UX in non-obvious ways. It's not an automatic replacement.

FAQ

Did useEffect become obsolete in React 19?

No. The React team didn't deprecate it or mark it as legacy. What changed is that React 19 puts better tools within reach for the cases where useEffect was previously the only available option. For subscriptions, integration with external DOM APIs, and synchronization with systems outside of React's model, useEffect is still correct.

Does use() replace useEffect for all fetches?

For fetches in client components that depend on user interaction, use() with Suspense is a concrete alternative. For initial data fetches in App Router, Server Components are the most direct answer — neither use() nor useEffect. The choice depends on whether the data can be resolved on the server or needs to wait for the client.

When to use useMemo vs direct calculation for derived state?

Direct calculation first. useMemo only when the calculation is measurably expensive (sort/filter over large arrays, complex transformations) and the profiler confirms there's an actual problem. Adding useMemo preemptively is just another form of over-engineering — it has a readability cost and the dependencies can also be wrong.

Does useActionState work without Server Actions?

Yes. useActionState accepts any async function, not just Server Actions. If you prefer to handle the submit on the client side, you can pass it a client-side function. The integration with Server Actions is the cleanest in Next.js with App Router, but it's not a requirement.

How do I migrate an existing codebase? Is there an incremental path?

The safest path is by category, not by file. Start by identifying all the useEffect calls that only derive state — they're the safest to migrate and give the most immediate benefit. Then the ones that react to user events. Fetches last, because they require decisions about Suspense boundaries that affect UX.

Do these patterns change if I'm using Zustand, Jotai, or Redux?

Partially. External stores solve the global state problem, but the antipattern of deriving state inside a component with useEffect shows up just the same. The question "can I calculate this during render?" applies regardless of which state management system you're using.


The judgment that doesn't come from the framework

What frustrated me most when I audited this codebase wasn't finding the antipatterns — that was expected. It was realizing they were there because at the time nobody had a clear rule for deciding when to use useEffect. We used it as the default tool for "do something when something changes," and that mental model is wrong from the start.

React 19 makes it easier to do the right thing: use() exists, useActionState exists, Server Components are more integrated. But without the judgment of when each tool applies, what happens is that the same problems just migrate to the new APIs.

My concrete take: before writing a useEffect, ask yourself whether what you want to do is (a) calculate something from existing state, (b) react to a user action, (c) load data, or (d) sync with something external to React. Only the last case justifies an effect. The first three have better solutions in React 19, and the official React documentation says so explicitly.

If you're auditing a codebase and don't know where to start, the same audit exercise applies to other patterns: the N+1 that shows up when you least expect it in Prisma has the same structure — a pattern that seems reasonable until you look at it with the right question.


Original source: