
Imperative Routing in NextJS
π Imperative Routing in Next.js
Next.js provides imperative routing using the useRouter
hook from next/router
. This allows programmatic navigation, unlike declarative routing (which relies on <Link>
components).
π 1. Basic Imperative Navigation
Use the useRouter
hook to navigate between pages dynamically:
<div> <h1>Home Page</h1> <button onClick={goToAbout}>Go to About</button> </div> );}
β
Allows navigation without <Link>
β
Great for button-based routing
π 2. Navigating with Dynamic Routes
Pass dynamic parameters using query strings:
const router = useRouter();router.push("/product?itemId=123");
Or navigate with URL parameters:
router.push("/product/123");
π 3. Using replace()
Instead of push()
πΉ push()
(Adds to History)
router.push("/dashboard");
β User can go back using the browserβs back button
πΉ replace()
(Does Not Add to History)
router.replace("/dashboard");
β Better for login redirects (prevents back navigation)
π 4. Navigating with State (Shallow Routing)
Shallow routing allows updating the URL without reloading the page.
router.push("/profile", undefined, { shallow: true });
β Useful for updating query params without full page reload
π 5. Redirecting Users After an Action
Redirect users after form submission or authentication:
const handleLogin = () => { // Perform login logic router.push("/dashboard");};
β Seamless user experience
π 6. When to Use Imperative Routing?
βοΈ Button-based navigation (e.g., "Go Back" button)
βοΈ Programmatic redirects after login/logout
βοΈ Dynamic route navigation (e.g., /product/:id
)