title: Server side rendered element should be scrolled to bottom on initial render
body: <p>I’m building a React server side rendered application (Next.js) and have a scrollable <code>&lt;div&gt;</code> that I want to be scrolled to the bottom on initial load of the page before React has hydrated the component.</p>
  <p>That means a <code>useLayoutEffect()</code> hook like the following is not sufficient because there will be a brief flash of the element scrolled to the top before React mounts and runs this hook.</p>
  <pre><code>useLayoutEffect(() =&gt; {
    const element = ref.current;
    element.scrollTop = element.scrollHeight - element.clientHeight;
  });
  </code></pre>
  <p>The approach that I think will work to prevent this is adding a <code>&lt;script&gt;</code> tag in the server side rendered page. For example:</p>
  <pre><code>function MyComponent() {
    return (
      &lt;&gt;
        &lt;div style={{overflowY: &quot;scroll&quot;}}&gt;
          ...
        &lt;/div&gt;
        &lt;script&gt;
          var element = document.currentScript.previousElementSibling;
          element.scrollTop = element.scrollHeight - element.clientHeight;
        &lt;/script&gt;
      &lt;/&gt;
    );
  }
  </code></pre>
  <p>However, I’ve found that when the <code>&lt;script&gt;</code> executes the <code>clientHeight</code> of the <code>&lt;div&gt;</code> element is 0.</p>
  <p>Presumably, I need to wait for the browser to finish loading the DOM so I added a <code>DOMContentLoaded</code> listener:</p>
  <pre><code>function MyComponent() {
    return (
      &lt;&gt;
        &lt;div style={{overflowY: &quot;scroll&quot;}}&gt;
          ...
        &lt;/div&gt;
        &lt;script&gt;
          var element = document.currentScript.previousElementSibling;
          document.addEventListener(&quot;DOMContentLoaded&quot;, function() {
            element.scrollTop = element.scrollHeight - element.clientHeight;
          });
        &lt;/script&gt;
      &lt;/&gt;
    );
  }
  </code></pre>
  <p>However, with this approach it appears the browser still does a paint with <code>scrollTop</code> set to 0 and then processes the <code>DOMContentLoaded</code> event handler.</p>
  <p>How can I write a <code>&lt;script&gt;</code> here that executes the “scroll to bottom” behavior <em>after</em> DOM properties like <code>element.clientHeight</code> have loaded but <em>before</em> the first browser paint so the user doesn’t see a flash of the wrong scroll position.</p>
  <p>Is there a better approach than this?</p>