In Next.js, you can use the Router object from next/router or the useRouter hook to change URLs without refreshing the page, primarily implemented using the HTML5 History API. This approach is commonly used for building Single-Page Applications (SPAs), enhancing user experience by providing smoother navigation.
Here are several common methods:
1. Using Router.push or Router.replace
The Router.push method changes the URL and adds a new history entry, while Router.replace replaces the current history entry. If you don't want the changed URL to be added to the browser's history stack, use Router.replace.
Example code:
javascriptimport { useRouter } from 'next/router' function MyComponent() { const router = useRouter(); const handleClick = () => { router.push('/new-page') } return ( <button onClick={handleClick}>Go to new page</button> ) }
2. Using the Link Component
Next.js provides a Link component that allows you to change URLs declaratively. When using the Link component, the page won't fully refresh; only the new content will be loaded.
Example code:
javascriptimport Link from 'next/link' function NavigationMenu() { return ( <nav> <Link href="/about"> <a>About Us</a> </Link> <Link href="/services"> <a>Our Services</a> </Link> <Link href="/contact"> <a>Contact Us</a> </Link> </nav> ) }
3. Using Dynamic Routing
Next.js also supports dynamic routing, which allows you to dynamically change URLs based on data. For example, if you have a blog and want to display different articles based on the article ID.
Example code:
javascriptimport { useRouter } from 'next/router' function Post() { const router = useRouter() const { pid } = router.query return <p>Post: {pid}</p> }
In the above code, if you access /post/1, the component will display 'Post: 1'.
By using these methods, Next.js simplifies changing URLs without page reloads and is highly efficient. This not only enhances user experience but also helps in building modern, efficient web applications.