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

Viewed 454

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

For example:

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

Is that any different from:

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

UPDATE:

This will run on the 1st time I render my component. I don't want my users to see any flickering (i.e: I just want them to see the "already" scrolled to bottom situation). In this case, will useLayoutEffect allow me to achieve this behavior? By doing things synchronously before allowing the browser to re-paint?

1 Answers

The difference is following.

useEffect runs asynchronously after the render is committed to the screen.

useLayoutEffect on the other hand based on docs runs:

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.

Because of this if you update screen in useEffect you may notice some blink effect sometimes. Because screen was updated then you immediately updated it again in useEffect.

But most of the times you probably need useEffect. Docs:

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

Related