fix(useWebSocket): replace ref+useMemo pattern with useState+useEffect in demo#2917
Draft
fix(useWebSocket): replace ref+useMemo pattern with useState+useEffect in demo#2917
Conversation
|
|
…ffect in useWebSocket demo Agent-Logs-Url: https://github.com/alibaba/hooks/sessions/1a77d062-ee53-4401-83fa-2872626cf1b1 Co-authored-by: crazylxr <16161407+crazylxr@users.noreply.github.com>
Copilot
AI
changed the title
[WIP] Fix UI rendering issue with useWebsocket and ref usage
fix(useWebSocket): replace ref+useMemo pattern with useState+useEffect in demo
Mar 28, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The
useWebSocketdemo tracked message history viauseRef+useMemo, mutatingref.currentduring render. This pattern is confusing and non-idiomatic — it only worked incidentally becauselatestMessagestate changes triggered re-renders.[English Template / 英文模板]
🤔 这个变动的性质是?
🔗 相关 Issue
用户在 issue 中指出 demo 里
ref.current = useMemo(...)的写法不是常规模式,并询问其合理性。💡 需求背景和解决方案
旧写法(非惯用模式):
在渲染期间直接对
ref.current赋值属于副作用,且ref变化本身不触发重渲染——此处能正常工作只是因为latestMessage状态变化恰好触发了重渲染,属于隐式依赖,容易误导开发者。新写法(惯用模式):
使用
useState管理需要渲染的数据,使用useEffect响应latestMessage变化,符合 React 标准模式。📝 更新日志
useWebSocketdemo: replaced non-idiomaticuseRef+useMemomessage history pattern with standarduseState+useEffectuseWebSocket演示代码:将非惯用的useRef+useMemo消息历史写法替换为标准的useState+useEffect写法☑️ 请求合并前的自查清单
🔒 GitHub Advanced Security automatically protects Copilot coding agent pull requests. You can protect all pull requests by enabling Advanced Security for your repositories. Learn more about Advanced Security.