渲染后滚动到底部是否是 useLayoutEffect 的良好用例?

Is scrolling to bottom after render a good use case for useLayoutEffect?

渲染后滚动到底部是否是 useLayoutEffect 的良好用例?

例如:

useLayoutEffect(() => {
  const element = divRef.current;
  const { scrollHeight } = element;
  element.scrollTop = scrollHeight;
}, []);

这与以下有什么不同吗:

useEffect(() => {
  const element = divRef.current;
  const { scrollHeight } = element;
  element.scrollTop = scrollHeight;
}, []);

更新:

这将在我第一次呈现我的组件时 运行。我不希望我的用户看到任何闪烁(即:我只希望他们看到“已经”滚动到底部的情况)。在这种情况下,useLayoutEffect 会允许我实现这种行为吗?通过在允许浏览器重新绘制之前同步执行操作?

区别如下

useEffect 运行异步 渲染提交到屏幕后。

另一方面,

useLayoutEffect 基于 docs 运行:

synchronously after all DOM mutations. Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside useLayoutEffect will be flushed synchronously, before the browser has a chance to paint.

所以首先 useLayoutEffect 必须完成,然后 然后 渲染将提交到屏幕。使用 useEffect,首先在屏幕上提交渲染,然后 useEffect 异步运行。

因此,如果您在 useEffect 中更新屏幕,有时您可能会注意到一些闪烁效果。因为屏幕已更新,所以您立即在 useEffect.

中再次更新了它

但大多数时候您可能需要 useEffect。文档:

Prefer the standard useEffect when possible to avoid blocking visual updates.