/

How to Force a Page Refresh in Next.js

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
2
3
4
5
6
7
import { useRouter } from 'next/router'

// ...

const router = useRouter()

router.reload(window.location.pathname)

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
2
3
import Router from 'next/router'

Router.reload(window.location.pathname)

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”]