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

推荐订阅源

N
Netflix TechBlog - Medium
J
Java Code Geeks
爱范儿
爱范儿
雷峰网
雷峰网
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 三生石上(FineUI控件)
H
Hackread – Cybersecurity News, Data Breaches, AI and More
B
Blog RSS Feed
Google DeepMind News
Google DeepMind News
Jina AI
Jina AI
The GitHub Blog
The GitHub Blog
I
InfoQ
月光博客
月光博客
博客园 - 聂微东
博客园 - Franky
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
G
Google Developers Blog
Blog — PlanetScale
Blog — PlanetScale
L
LangChain Blog
罗磊的独立博客
Apple Machine Learning Research
Apple Machine Learning Research

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
useOptimistic + useActionState: React 19 Killed 50 Lines ...
Vitalii · 2026-06-28 · via DEV Community

Vitalii

Every form submission in React used to look like this:

const [data, setData] = useState(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)

async function handleSubmit(e) {
  e.preventDefault()
  setLoading(true)
  try {
    const result = await submitToServer(formData)
    setData(result)
  } catch (err) {
    setError(err.message)
  } finally {
    setLoading(false)
  }
}

Three useState calls. A try/catch/finally. Manual loading and error flags. And that's without optimistic updates — add those and you're looking at another 20 lines of snapshot/revert logic.

React 19 ships two hooks that delete most of this.


useActionState — form lifecycle in one hook

const [error, submitAction, isPending] = useActionState(
  async (prevState, formData) => {
    const res = await fetch('/api/submit', {
      method: 'POST',
      body: formData,
    })
    if (!res.ok) return 'Something went wrong'
    return null
  },
  null
)

return (
  <form action={submitAction}>
    <input name="email" type="email" />
    <button disabled={isPending}>
      {isPending ? 'Sending...' : 'Submit'}
    </button>
    {error && <p>{error}</p>}
  </form>
)

isPending is automatic. Error state is the return value of your action. No useState, no try/catch wrappers, no finally.


useOptimistic — instant UI without manual rollback

The old way of doing a like button:

// snapshot → update → revert on error = ~30 lines

The React 19 way:

const [optimisticLikes, addOptimisticLike] = useOptimistic(
  likes,
  (current, increment) => current + increment
)

async function handleLike() {
  addOptimisticLike(1)      // instant UI
  await likePost(postId)    // server confirms
}

return <button onClick={handleLike}>❤️ {optimisticLikes}</button>

That's it. If the server call fails, React automatically reverts to the real value — no manual rollback code needed. The optimistic state is just a temporary layer that disappears when the action settles.


One important gotcha

addOptimistic must be called before any await in your action. React's transition system only captures optimistic updates issued synchronously before the first suspension point. Call it after an await and the update won't show up.

// ✅ correct
addOptimisticLike(1)
await likePost(postId)

// ❌ won't work
await someOtherThing()
addOptimisticLike(1)


When to still use React Query / SWR

These hooks are for component-local action state. If your mutation needs to invalidate a cache shared across multiple components, you still want React Query or similar. But for the submit-and-respond pattern that covers the majority of forms and mutations in a typical app — these built-ins are now the right default.