Use useRouter when you need to programmatically navigate between pages, update the query string, or perform other navigation-related tasks in response to user input or other events. For example, you might use useRouter to update the query string when a user selects a filter in a product listing page, or to navigate to a new page when a user submits a form.
Programmatic navigation means using code to change the current URL and navigate to a different page in your Next.js application. You might do this in response to user input, such as when a user clicks a button or selects an item from a dropdown menu, or in response to other events in your application.
Here are some examples of how to use useRouter for programmatic navigation in Next.js:
- Basic navigation
import { useRouter } from 'next/router';
function MyComponent() {
const router = useRouter();
const handleClick = () => {
router.push('/about');
};
return (
<button onClick={handleClick}>
Go to about page
</button>
);
}
In this example, we import the useRouter hook from the next/router module and use it to access the router object. We then define a function handleClick that uses the push method of the router object to navigate to the /about page when the button is clicked.
- Navigation with query parameters
import { useRouter } from 'next/router';
function MyComponent() {
const router = useRouter();
const handleClick = () => {
router.push({
pathname: '/product',
query: { id: '123' },
});
};
return (
<button onClick={handleClick}>
View product details
</button>
);
}
In this example, we use the push method of the router object to navigate to the /product page with a query parameter id set to 123. We pass an object to the push method with two properties: pathname and query. The pathname property specifies the path of the page to navigate to, and the query property specifies any query parameters to include in the URL.
- Conditional navigation
import { useRouter } from 'next/router';
function MyComponent() {
const router = useRouter();
const handleSearch = (query) => {
if (query.length > 0) {
router.push(`/search?q=${query}`);
}
};
return (
<form onSubmit={(e) => {
e.preventDefault();
handleSearch(e.target.query.value);
}}>
<input type="text" name="query" />
<button type="submit">Search</button>
</form>
);
}
In this example, we define a function handleSearch that is called when the user submits a search form. If the search query is not empty, we use the push method of the router object to navigate to the search results page with the query parameter set to the user's input. If the search query is empty, we don't navigate anywhere.
These are just a few examples of how you can use useRouter to programmatically navigate between pages in your Next.js application. The router object provides many other methods and properties that you can use to customize your navigation behavior, so I encourage you to read the Next.js documentation for more information.