How to force a page refresh in Next.js

By

Learn how to force a full page refresh in Next.js with the useRouter hook and router.reload(), or the imported Router object when you are outside a component.

~~~

To force a page refresh in Next.js you call router.reload(). It performs a full browser reload of the current page, like when you press the reload button.

In a component, you get the router object with the useRouter hook:

import { useRouter } from 'next/router'

//...

const router = useRouter()

router.reload()

router.reload() takes no arguments. Under the hood it calls window.location.reload(), so the browser throws away the current page and loads it again from scratch.

Sometimes you can’t use the hook, for example when you’re not in a React component, maybe in a utility function. Hooks only work inside components.

In that case, import the global Router object instead:

import Router from 'next/router'

Router.reload()

When would you need this?

A full reload resets everything: component state, in-memory caches, third-party scripts. I reach for it when the client is too out of sync with the server to patch things up, for example after a logout, or when a setting changed and half the page depends on it.

One thing to remember: reload() only works in the browser. During server-side rendering there’s no window, so calling it there fails. Call it in event handlers or inside useEffect, never in the component body.

Be careful: you lose all client state

A full reload is a heavy tool. Form inputs, scroll position, anything stored in React state, it’s all gone.

Often what you actually want is not a reload, but fresh data from getServerSideProps. You can get that without reloading, by navigating to the page you’re already on:

router.replace(router.asPath)

router.asPath is the current URL as shown in the browser. Navigating to it makes Next.js call getServerSideProps again and render the page with the new props, while React stays mounted, so client state survives.

I used replace() instead of push() here on purpose. push() would add a new entry to the browser history, and pressing back would return to the same page. replace() swaps the current entry, which is what you want for a refresh.

Tagged: Next.js · All topics
~~~

Related posts about next: