[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.

 

posted @   Zhentiw  阅读(54)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源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
点击右上角即可分享
微信分享提示