Page does not automatically scroll to the top when switching routes React JS

February 18, 2023

There is a common issue that is faced by many developers during developing a React app which is page is not automatically scrolled to the top after route changes. Although this issue is not present in frameworks like Gatsby and Next JS. This issue arises when we are using the core React or CRA.

 

I have come up with solutions that can be helpful in solving this issue.

1. Using the useLayoutEffect hook

With the help of the useLayoutEffect hook, this issue can be solved easily. You might be wondering why using useLayotEffect and not our friend useEffect hook.

This is because we want the scroll to happen after the DOM is painted but before the screen is painted. This is important because if the effect were to take place before the DOM is painted, the user would briefly see the page in the same position before it is scrolled to the top.

 

Here is a code example for the same.

 

code snippet for useLayoutEffect hook

 

Just import this component into the app.js file and you are good to go.

Optional: You can create a custom hook out of this. If you need one just comment below the post.

  1. Using ScrollRestoration from react-router-dom

With React router dom version 6.4, they introduced a data router. They added a scroll restoration component that is able to solve this issue as well. The only downside is using the latest version to get this feature enabled.

 

Here is a code example for the same.

 

code snippet for useLayoutEffect hook

 

There are many optional props to this one can read it here.

ScrollRestoration Detailed Guide

 

Conclusion

There are many ways to solve this issue. I have personally used the first method to solve this scrolling issue on many websites that are in production. Consider using useLayoutEffect instead of useEffect to get better results.