How to Force a Page Refresh in Next.js
In Next.js, there may be situations where you need to manually force a page refresh. Whether you are working within a component using the useRouter
hook or in a utility function, this guide will show you how to achieve a page refresh in both scenarios.
Using the useRouter
Hook
To force a page refresh within a component using the useRouter
hook, follow these steps:
1 | import { useRouter } from 'next/router' |
By accessing the useRouter
hook, you can obtain the router
object which provides various methods and properties to control navigation and page status. In this example, router.reload()
is used to refresh the page by providing the current path obtained from window.location.pathname
.
Without Using the useRouter
Hook
If you are not in a React component, such as in a utility function, you can still achieve a page refresh by utilizing the Router
object from Next.js:
1 | import Router from 'next/router' |
By directly importing the Router
object and invoking the reload()
method with the current path, you can successfully force a page refresh without needing the useRouter
hook.
Incorporating these approaches into your Next.js project will allow you to easily trigger a page refresh whenever necessary.
tags: [“Next.js”, “page refresh”, “useRouter”, “Router”, “utility function”]