[React] Flushing state updates synchronously with flushSync
In React, every update is split in two phases:
- During render, React calls your components to figure out what should be on the screen.
- During commit, React applies changes to the DOM.
React sets ref.current
during the commit. Before updating the DOM, React sets the affected ref.current
values to null
. After updating the DOM, React immediately sets them to the corresponding DOM nodes.
In React, state updates are queued.
setTodos([ ...todos, newTodo]);
listRef.current.lastChild.scrollIntoView();
setTodos
does not immediately update the DOM.
So the time you scroll the list to its last element, the todo has not yet been added. This is why scrolling always “lags behind” by one item.
To fix this issue, you can force React to update (“flush”) the DOM synchronously. To do this, import flushSync
from react-dom
and wrap the state update into a flushSync
call:
flushSync(() => {
setTodos([ ...todos, newTodo]);
});
listRef.current.lastChild.scrollIntoView();
This will instruct React to update the DOM synchronously right after the code wrapped in flushSync
executes.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2022-03-20 [AWS - Solution Architect] Solution Architect for Database
2021-03-20 [AWS] Signed URL partten
2021-03-20 [Postgres] Create VIEW for display join tables result
2021-03-20 [Git] A better git process
2021-03-20 [Postman & Integration Tests] Using Postman to Define Integration Tests
2020-03-20 [HTML 5] Using DocumentFragments
2019-03-20 [Algorithm] Count occurrences of a number in a sorted array with duplicates using Binary Search