Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Tue May 23 2023

How to automatically scroll a page to the top once navigated to in React

In this tutorial, we will show how we can implement a scroll to top functionality in our React application so that our pages always starts at the top when being navigated to. We will create a custom hook that we will call from all our pages.

Problem

Often when we have pages that are quite long and the user needs to scroll down to read and see the content, the next page that they will navigate to will start at the same scrolling position as the last page. It is not always the case, it is more dependent on the routing we are using. The problem is more related to client-side routing if you ask me. In this tutorial, we will solve the issues with not having the pages start at the top.

Create our custom hook

Let's create a file called useScroll.tsx (.jsx) in our project. And add following code

import { useEffect } from "react"; export const useScroll = () => { useEffect(() => { window.scroll({ left: 0, top: 0, behavior: "smooth" }); }, []); };

What this function is basically doing, is automatically scrolling to the top with a smooth behaviour (if supported). You can skip the behaviour if you don't want it to be smooth, then it will move much faster.

Consume our hook

And in all pages that we want the scroll to top functionality, we just call it like this:

import { useScroll } from "hooks/useScroll"; const MyPage = () => { useScroll(); return <div>My page</div>; };

And there we go!

Outro

Today we showed how we can make our pages always start at the top, using a custom hook and the built in scroll() function from the window object in JavaScript. I hope you liked this short guide, and thanks for reading.

All the best,

signatureTue May 23 2023
See all our articles