Mastering Next.js useRouter: Usage and Options Guide

0

Next.js is a React framework that supports Server-Side Rendering (SSR) and Static Site Generation (SSG), making it highly beneficial for SEO. The router functionality in Next.js makes it easy to handle page navigation and URL management. By using the `useRouter` hook, you can easily implement client-side routing. This guide will delve into the usage of `useRouter`, various options, and practical applications.

1. Basic useRouter Usage

`useRouter` is a hook provided by Next.js, offering various functionalities related to client-side routing.

import { useRouter } from 'next/router';

const MyComponent = () => {
    const router = useRouter();
    
    // Get the current path and query parameters.
    const { pathname, query } = router;
    
    return (
        <div>
            <p>Current path: {pathname}</p>
            <p>Query parameters: {JSON.stringify(query)}</p>
        </div>
    );
};

2. router.push Method and Options

The `router.push` method is used for navigating between pages. It changes the URL and updates the page without a full reload.

Basic Usage

const handleClick = () => {
    router.push('/new-page');
};

Adding Query Parameters

router.push({
    pathname: '/new-page',
    query: { search: 'keyword' },
});

Shallow Option

The `shallow` option is used to change the URL without reloading the page.

router.push('/new-page', undefined, { shallow: true });

Example Code Review

Here is a simple sample code:

import { useRouter } from 'next/router';

const router = useRouter();
const type = 'example'; // Example type variable

router.push(
    {
        pathname: router.pathname,
        query: {
            ...router.query,
            searchType: type,
        },
    },
    `/new-path?searchType=${type}`,
    { shallow: true },
);

How It Works

First Argument:
`{ pathname: router.pathname, query: { …router.query, searchType: type } }` : Defines the actual path and query parameters to navigate to. For example, if the current path is `/current-path` and the query parameters are `{ page: 1 }`, this object becomes `{ pathname: ‘/current-path’, query: { page: 1, searchType: ‘example’ } }`.
Second Argument:
`/new-path?searchType=example` : The URL displayed in the browser’s address bar. This URL is shown in the address bar but does not affect the actual navigation path.
Third Argument:
`{ shallow: true }` : Changes the URL without reloading the page.

Result

  • Navigation Path: The actual navigation path is defined by the first argument, including the path and query parameters. Next.js router loads the page based on `{ pathname: ‘/current-path’, query: { page: 1, searchType: ‘example’ } }`.
  • Displayed Path: The browser address bar shows `/new-path?searchType=example`, making it easy for users to understand and share the URL.

3. router.replace Method

The `router.replace` method works similarly to `router.push`, but it replaces the current entry in the browser’s history stack instead of adding a new one.

router.replace('/new-page');

4. router.prefetch Method

The `router.prefetch` method preloads a page, enhancing user experience. It is automatically applied to link tags.

useEffect(() => {
    router.prefetch('/new-page');
}, []);

5. router.events Events

Next.js router provides various events for page navigation. For example, you can display a loading state.

import { useRouter } from 'next/router';
import { useEffect } from 'react';

const MyComponent = () => {
    const router = useRouter();

    useEffect(() => {
        const handleRouteChange = (url) => {
            console.log('App is changing to: ', url);
        };

        router.events.on('routeChangeStart', handleRouteChange);

        return () => {
            router.events.off('routeChangeStart', handleRouteChange);
        };
    }, []);

    return <div>MyComponent</div>;
};

6. Practical Applications

Search Filtering

const handleFilterChange = (filter) => {
    router.push({
        pathname: router.pathname,
        query: { ...router.query, filter },
    }, undefined, { shallow: true });
};

Dynamic Routing

router.push('/product/[id]', `/product/${productId}`);

7. SEO Optimization Strategies

Utilize Next.js routing features to optimize your site for SEO. Create meaningful URL structures and enhance user experience with client-side navigation.

  • Meaningful URL: Simplify URLs, for example, use `/shoes` instead of `/products/shoes`.
  • Meta Tags: Set appropriate meta tags for each page to provide information to search engines.
import Head from 'next/head';

const SEO = () => (
    <Head>
        <title>My SEO Title</title>
        <meta name="description" content="My SEO description" />
        <meta name="keywords" content="nextjs, seo, tutorial" />
    </Head>
);

Conclusion

We have explored Next.js `useRouter` in this guide. By mastering the `useRouter` hook, you can efficiently implement routing functionality and build an SEO-optimized website with Next.js.

Leave a Reply