Next.js - useAmp Function



In Next.js useAmp function is used to check if a page is AMP page. In this chapter we will learn what is useAmp function, how to use it, syntax and example usage of useAmp method.

Next.js useAmp Method

The useAmp method in Next.js is a utility that is used to detect if the current page is being rendered as an AMP (Accelerated Mobile Pages) page. AMP is a web component framework for building fast-loading web pages. Learn more about AMP and AMP pages from our AMP tutorial.

Syntax

Following is syntax of useAmp method.

// Import the library
import { useAmp } from 'next/amp';

export const config = { amp: 'hybrid' };  

export default function Home() {
    const isAmp = useAmp();
}
  • Arguments: The useAmp method doesn't take any arguments.
  • Return Type: It return a boolean value. True if the page is rendered in AMP mode and false if page is not rendered in AMP mode.

Key Points about useAmp

  • The useAmp hook is typically used within a React component on pages that support AMP, so that you can conditionally render content based on whether the page is in AMP mode or not.
  • This method is only supported in pages router, in App router you can implement AMP functionality with the new server-side data fetching methods.
  • The AMP have two mode, AMP-only mode means the pages are exclusively rendered in AMP format and Hybrid-AMP mode means the pages are rendered in both AMP and standard modes, depending on the URL.

Enabling AMP in Next.js

To enable AMP for a page in Next.js, you can use one of these configurations.

// AMP-only Mode:
export const config = { amp: true };

// Hybrid AMP Mode:
export const config = { amp: 'hybrid' };

Example of Using useAmp

The code below shows how to use the useAmp method in Next.js. We created a button that toggles between AMP version and Non Amp version of same page. See the output below.

// pages/index.tsx

import { useAmp } from 'next/amp';

export const config = { amp: 'hybrid' }; // Enable Hybrid AMP mode

export default function Home() {
  const isAmp = useAmp();

  return (
    <div>
      <h1>Welcome to Next.js with AMP</h1>
      {isAmp ? (
        <p>You are viewing the AMP version of this page.</p>
      ) : (
        <p>You are viewing the standard version of this page.</p>
      )}
      <a href={isAmp ? '/' : '/?amp=1'}>
        Switch to {isAmp ? 'Standard' : 'AMP'} Mode
      </a>
    </div>
  );
}

Output

In the output, AMP mode is getting toggled on clicking the link.

next.js-useamp-function
Advertisements