在 React 中使用 useEffectEvent

useEffectEvent is a React Hook that allows you to extract non-reactive logic from Effects. It solves the common problem where you need to read the latest value of props or state inside an Effect without causing that Effect to re-run when those values change.

useEffectEvent 是一个 React Hook,允许你从 Effects 中提取非反应式逻辑。它解决了一个常见问题,即你需要在 Effect 中读取 props 或 state 的最新值,而不会在这些值变化时导致该 Effect 重新运行。

Key Concept: useEffectEvent creates a stable function reference that always reads the latest values, but doesn't trigger Effect re-execution when those values change.

关键概念: useEffectEvent 创建一个稳定的函数引用,该引用始终读取最新值,但在这些值变化时不会触发 Effect 重新执行。

Consider a chat application where you want to log a message when the room changes, but you need to include the current theme in your log. Traditionally, you'd need to add theme to the dependency array, causing the Effect to re-run every time the theme changes, even though you only want to react to room changes.

考虑一个聊天应用程序,当房间发生变化时,您希望记录一条消息,但您需要在日志中包含当前主题。传统上,您需要将主题添加到依赖数组中,这会导致每次主题变化时 Effect 重新运行,即使您只想对房间变化做出反应。

❌ Traditional Problem:

❌ 传统问题:

useEffect(() => {
  logVisit(roomId, theme); // Re-runs when theme changes
}, [roomId, theme]); // Had to include theme!

✅ With useEffectEvent:

✅ 使用 useEffectEvent:

const onVisit = useEffectEvent((roomId) => {
  logVisit(roomId, theme); // Reads latest theme
});

useEffect(() => {
  onVisit(roomId); // Only re-runs when roomId changes
}, [roomId]);

Do's and Don'ts

注意事项

✓ DO

✓ 可以

  • Use it to read the latest props/state without adding them to dependencies
  • 使用它来读取最新的 props/state,而无需将它们添加到依赖项中
  • Call it directly from inside Effects
  • 直接在 Effects 中调用它
  • Use it for event handlers that need to access Effect context
  • 将其用于需要访问 Effect 上下文的事件处理程序
  • Use it to separate reactive and non-reactive logic
  • 使用它来分离反应和非反应逻辑
  • Call it synchronously within your Effect
  • 在你的 Effect 中同步调用它

✗ DON'T

✗ 不可以

  • Don't call it from regular event handlers
  • 不要从常规事件处理程序中调用它
  • Don't call it during rendering
  • 不要在渲染期间调用它
  • Don't pass it as a prop to components
  • 不要将其作为属性传递给组件
  • Don't call it asynchronously or after a delay
  • 不要异步调用或延迟后调用
  • Do...
开通本站会员,查看完整译文。

Accueil - Wiki
Copyright © 2011-2025 iteam. Current version is 2.148.2. UTC+08:00, 2025-12-17 13:37
浙ICP备14020137号-1 $Carte des visiteurs$