This video is available to students only

useLayoutEffect & Window Scroll

If we were to navigate from page to page in our app, we'll notice that in certain cases the window scroll position of the page doesn't scroll to the top when we would expect it to.

Since our application is a client-side app, the server returns a single web-page at the beginning. When we navigate from route to route (i.e. page to page), the parent <App /> component simply determines which child component should be shown (e.g. <Host /> component is shown in the /host route). When different child components get rendered as we move from page to page, the scroll position of the window can remain the same which can cause the issue of having the new page that is shown be in a scroll position close to the bottom of the page.

To avoid this, we can have an effect run whenever a section-level child component is rendered to scroll the window to the top of the page. To run an effect with DOM specific changes, we should use the useLayoutEffect Hook from React. This is because the useLayoutEffect Hook fires synchronously after all DOM mutations and thus should be used to read and/or change layout in the DOM.

We'll consolidate the effect we want to run within a custom effect we'll call useScrollToTop. We'll create this custom effect in a /hooks folder within the src/lib/ directory of our client application.

client
  src/
    lib/
      // ...
      hooks/
        useScrollToTop/
          index.ts
      index.ts
  // ...
// ...

In the src/lib/hooks/index.ts file, we'll re-export the soon to be created useScrollToTop() function.

client/src/lib/hooks/index.ts
export * from "./useScrollToTop";
No discussions on video yet