[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 @ 2023-03-20 22:03  Zhentiw  阅读(47)  评论(0编辑  收藏  举报