0
0
NextJSframework~5 mins

Programmatic navigation (useRouter) in NextJS - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is useRouter in Next.js?

useRouter is a React hook provided by Next.js that lets you access the router object. It helps you navigate pages programmatically and get info about the current route.

Click to reveal answer
beginner
How do you navigate to a new page using useRouter?
<p>You call <code>router.push('/path')</code> where <code>router</code> is the object from <code>const router = useRouter()</code>. This changes the page to the given path.</p>
Click to reveal answer
intermediate
What is the difference between router.push() and router.replace()?

router.push() adds a new entry in the browser history, so users can go back. router.replace() changes the page without adding a new history entry, replacing the current one.

Click to reveal answer
intermediate
How can you pass query parameters when navigating programmatically with useRouter?

You can pass an object to router.push() like router.push({ pathname: '/search', query: { q: 'books' } }). This adds ?q=books to the URL.

Click to reveal answer
beginner
Why use programmatic navigation instead of <Link> in Next.js?

Programmatic navigation is useful when you want to navigate after an event like form submission or button click, where you need to run code before changing pages.

Click to reveal answer
Which hook do you use in Next.js for programmatic navigation?
AuseLink
BuseNavigate
CuseHistory
DuseRouter
What does router.push('/about') do?
AReloads the current page
BNavigates to the /about page and adds to browser history
CNavigates to /about but replaces current history entry
DDoes nothing
How do you replace the current page without adding a new history entry?
Arouter.replace('/newpage')
Brouter.push('/newpage')
Crouter.goBack()
Drouter.reload()
How to add query parameters when navigating with useRouter?
Arouter.query({ q: 'books' })
Brouter.push('/search?q=books')
Crouter.push({ pathname: '/search', query: { q: 'books' } })
Drouter.navigate('/search', { q: 'books' })
When is programmatic navigation preferred over using <Link>?
AAfter an event like form submission
BFor static links in navigation menus
CWhen you want to reload the page
DNever, <code>&lt;Link&gt;</code> is always better
Explain how to use useRouter to navigate to a new page with query parameters in Next.js.
Think about how to pass both the page path and extra info in the URL.
You got /4 concepts.
    Describe the difference between router.push() and router.replace() in Next.js navigation.
    Consider how browser back button behaves after each method.
    You got /4 concepts.