The Built-in `back` Method in NextJS

Yasir Gaji
1 min readMar 4, 2024

--

Here’s a more effective way to implement a back button method using the Next.js router history feature hookuseRouter.back()

An Image showing the implementation of the useRouter hook by Yasir Gaji
The implementation of the useRouter hook image by Yasir Gaji

Take the image above for instance import useRouter from next/router , then in your component define a function handleBackClick which would trigger the router.back() method.

When this button is clicked/triggered in the UI the router.back() method would access the browser history and navigate the user back one step. This is a faster way compared to defining a Routes utils and variables and using the Link method with it.

Note

  • The router.back() method relies on the browser's history stack. If the user navigates away from your application and then clicks the back button, they might not necessarily land on the previous page within your app.
  • Consider using getStaticProps or getServerSideProps for data fetching on the previous page to ensure a smooth user experience upon navigation back.

Conclusion

I expect questions for clarification. Kindly criticize and make corrections as well. Share, Thank you.

--

--