How to Force a Page Refresh in Next.js

To force a page refresh in Next.js, we can utilize the next/router module to programmatically navigate to the current page with different query parameters. This triggers a full reload of the page.

Here’s an example of how we can achieve this:

import { useRouter } from ‘next/navigation’;
const MyComponent = () => {
const router = useRouter();
const handleRefresh = () => {
router.refresh();
};
return (
<div>
<button onClick={handleRefresh}>Refresh</button>
</div>
);
};
export default MyComponent;

In the example above, we import the useRouter hook from next/navigation to access the router object. We define a handleRefresh function that calls router.refresh() with the current router.pathname and undefined for the query parameters. By setting shallow to false, we ensure that a full page refresh occurs.

Finally, we attach the handleRefresh function to a button’s onClick event to trigger the page refresh when the button is clicked.

Remember to import the necessary modules and use this code within a component in your Next.js application.

Leave a comment

Your email address will not be published. Required fields are marked *