In Next.js, the useRouter
hook is a part of the next/router
module that allows you to access the router object and perform programmatic navigation. Here's a basic example of how to use the useRouter
hook for programmatic navigation:
jsx// Import the necessary modules
import { useRouter } from 'next/router';
import Link from 'next/link';
// Your component
function MyComponent() {
// Access the router object using the useRouter hook
const router = useRouter();
// Function to handle programmatic navigation
const handleClick = () => {
// Use the router.push method to navigate to a new page
router.push('/another-page');
};
return (
<div>
<p>Click the button to navigate to another page:</p>
{/* Example of using Link component for client-side navigation */}
<Link href="/another-page">
<a>Go to another page (Link)</a>
</Link>
{/* Button for programmatic navigation */}
<button onClick={handleClick}>Go to another page (Programmatic)</button>
</div>
);
}
export default MyComponent;
In this example:
useRouter
hook from next/router
.useRouter
hook within your functional component.router.push
method to navigate to the desired page. You can pass a string representing the URL or an object with the pathname
property.Additionally, the Link
component is also shown for comparison. The Link
component is useful for client-side navigation and provides a declarative way to create links between pages in your Next.js application.
Remember that Next.js supports both client-side and server-side navigation. The router.push
method performs client-side navigation, while Link
provides a convenient way to create links for client-side navigation as well. If you need to perform server-side navigation, you can use router.push
with the as
option or use the router.replace
method.