link in next js is refresh page
To create a link that refreshes the page in Next.js, you can follow these steps:
- Import the
useRouter
hook from thenext/router
module. This hook allows you to access the router object, which provides information about the current route and navigation methods.
import { useRouter } from 'next/router';
- Inside your functional component, initialize the
router
object by calling theuseRouter
hook.
const router = useRouter();
- Use the
router.reload()
method to refresh the page when the link is clicked. You can attach this method to an event handler, such as theonClick
event of a link element.
const handleRefresh = () => {
router.reload();
};
return (
<a href="#" onClick={handleRefresh}>
Refresh Page
</a>
);
In this example, we're attaching the handleRefresh
function to the onClick
event of an anchor (<a>
) element. When the link is clicked, the handleRefresh
function will be called, which in turn calls the router.reload()
method to refresh the page.
Note: The href="#"
attribute is used to make the link clickable, but it doesn't navigate to a specific URL. Instead, it triggers the onClick event handler.
And that's how you can create a link that refreshes the page in Next.js using the useRouter
hook and the router.reload()
method.