useOptimistic 无法拯救你

Updating the UI immediately in response to user interaction while the operation completes in the background. This decouples interface responsiveness from network latency. The canonical example is the "like" button.

在操作在后台完成的同时,立即响应用户交互更新 UI。这将界面响应性与网络延迟解耦。典型的例子是“点赞”按钮。

You would think implementing this in React would be simple, but doing it without introducing visual glitches or race conditions is not. React 19's useOptimistic hook appears to make the pattern a first-class citizen. However, I would argue that with the advent of Concurrent React, optimistic UI has gotten even more complicated and harder to implement.

你可能会认为在 React 中实现这个很简单,但要在不引入视觉故障或竞态条件的情况下实现它并不是。React 19 的 useOptimistic 钩子似乎使这种模式成为一流公民。然而,我认为随着 Concurrent React 的出现,optimistic UI 变得更加复杂和难以实现。

Let's explore why manual optimistic updates were historically fragile, how useOptimistic can help, and why it's not a silver bullet.

让我们探讨一下为什么手动乐观更新在历史上很脆弱,useOptimistic 如何帮助,以及为什么它不是万能药。

Where We Came From

我们从哪里来

To understand the architectural significance of useOptimistic, we should first examine the limitations of previous user-land implementations.

要理解 useOptimistic 的架构意义,我们应该首先检查之前用户空间实现的局限性。

Example 1. Bad Optimistic Update

示例 1. 糟糕的乐观更新

The most naive approach involves updating the UI on user interaction and again each time the server responds. There are a few issues here and a number of ways that the UI can get out of sync.

最天真的方法是在用户交互时更新 UI,并在服务器每次响应时再次更新。这里有一些问题,以及 UI 不同步的多种方式。

If we spam the button, the state flicks back and forth as the requests complete. If we randomize the latency we'll see race conditions and the final state becomes a toss up.

如果我们疯狂点击按钮,当请求完成时,状态会来回闪烁。如果我们随机化延迟,我们会看到竞态条件,最终状态就成了未知数。

Commenting out line #24 is a slight improvement. This stops the final sync with the server and solves the flickering, but it creates a new issue. If the UI goes out of sync it won't come back again until another bug occurs or the page is reloaded.

注释掉第 24 行是一个轻微的改进。这停止了与服务器的最终同步并解决了闪烁问题,但它创建了一个新问题。如果 UI 不同步,它不会再同步,直到发生另一个 bug 或页面重新加载。

With that line...

开通本站会员,查看完整译文。

首页 - Wiki
Copyright © 2011-2026 iteam. Current version is 2.148.4. UTC+08:00, 2026-01-24 20:21
浙ICP备14020137号-1 $访客地图$