
Navigation And Linking in NextJS
🔗 Navigation and Linking in Next.js
Next.js provides fast and efficient navigation using client-side routing. It supports both declarative and imperative routing methods for smooth page transitions.
📌 1. Declarative Navigation Using <Link>
Next.js provides the <Link>
component for navigation without a full page reload.
🔹 Basic Example
<button onClick={goToContact}>Go to Contact</button>;}
✅ Useful for buttons, form submissions, and redirects
📌 5. Navigating with replace()
Instead of push()
Use replace()
to navigate without adding to browser history:
router.replace("/dashboard");
✅ Prevents users from going back to the previous page
📌 6. Handling Back Navigation
const goBack = () => { router.back();};
✅ Allows users to return to the previous page programmatically
📌 7. Shallow Routing (Update URL Without Full Reload)
Use shallow routing to update the URL without fetching new data:
router.push("/profile", undefined, { shallow: true });
✅ Best for filter updates, tab navigation, or UI state changes
📌 8. External Links (New Tab & SEO Considerations)
<Link href="https://example.com" target="_blank" rel="noopener noreferrer"> Visit Example</Link>
✅ Prevents security risks while opening external sites
📌 9. When to Use Which Navigation Method?
Method | Use Case |
---|---|
<Link href="/about"> | Simple page-to-page navigation |
<Link href="/product/123"> | Dynamic route navigation |
router.push("/dashboard") | Redirects after form submission or login |
router.replace("/checkout") | Replace history (e.g., after a purchase) |
router.back() | Go back to the previous page |
router.push("/profile", undefined, { shallow: true }) | Update the URL without fetching new data |