Open In App

Create a Custom Hook to Make Next.js Apps Responsive

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Creating a custom hook for responsiveness in Next.js enables you to handle various screen sizes and device orientations effectively. This approach helps maintain a consistent user experience across different devices by encapsulating responsive logic into a reusable and manageable component.

Approach

To make your Next.js app responsive, create a custom hook that tracks the window size and updates when it changes. Use this hook to conditionally display mobile or desktop components, ensuring your app looks great on any device.

First Let's start by creating a Next.js project.

Steps to Create Next.js Project

Step 1: Initialize a new Next.js Project using the following command in the terminal:

npx create-next-app gfg-next

Step 2: Move to the project directory

cd gfg-next

Project Structure:

Step 3: Define the custom Hook in file /utils/useIsMobile.js

CSS
/* Home.module.css */
.container {
    padding: 0 2rem;
}

.main {
    min-height: 100vh;
    padding: 4rem 0;
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.title a {
    color: #0070f3;
    text-decoration: none;
}

.title a:hover,
.title a:focus,
.title a:active {
    text-decoration: underline;
}

.title {
    margin: 0;
    line-height: 1.15;
    font-size: 4rem;
}

.subtitle {
    line-height: 1.15;
    text-decoration: underline;
}

.title,
.description {
    text-align: center;
}

.description {
    margin: 4rem 0;
    line-height: 1.5;
    font-size: 1.5rem;
}

.code {
    background: #fafafa;
    border-radius: 5px;
    padding: 0.75rem;
    font-size: 1.1rem;
    font-family: Menlo, Monaco, Lucida Console, 
        Liberation Mono, DejaVu Sans Mono,
        Bitstream Vera Sans Mono, 
        Courier New, monospace;
}
JavaScript
//  Filename - utils/useIsMobile.js

import { useEffect, useState } from "react";

const useIsMobile = () => {
    const [width, setWidth] = useState(0);
    const handleWindowSizeChange = () => {
        setWidth(window.innerWidth);
    };

    useEffect(() => {
        handleWindowSizeChange();

        /* Inside of a "useEffect" hook add 
           an event listener that updates
           the "width" state variable when 
           the window size changes */
        window.addEventListener("resize", 
            handleWindowSizeChange);

        // Return a function from the effect 
        // that removes the event listener
        return () => {
            window.removeEventListener(
                "resize", handleWindowSizeChange);
        };
    }, []);

    return width <= 700;
};

export default useIsMobile;
JavaScript
// pages/index.js

import Head from "next/head";
import styles from "../styles/Home.module.css";
import useIsMobile from "../utils/useIsMobile";

export default function Home() {
    const isMobile = useIsMobile();

    return (
        <div className={styles.container}>
            <Head>
                <title>Create Next App</title>
                <link rel="icon" href="/favicon.ico" />
            </Head>
            {isMobile ? <Mobile /> : <Desktop />}
        </div>
    );
}

function Mobile() {
    return (
        <div className={styles.main}>
            <h1 className={styles.title}>
                Welcome to 
                    <a href="https://nextjs.org">
                    Next.js!
                </a>
            </h1>
            <h1 className={styles.subtitle}>
                Mobile UI
            </h1>
            <p className={styles.description}>
                Get started by editing mobile 
                component in
                <code className={styles.code}>
                    pages/index.js
                </code>
            </p>
        </div>
    );
}

function Desktop() {
    return (
        <div className={styles.main}>
            <h1 className={styles.title}>
                Welcome to 
                <a href="https://nextjs.org">
                    Next.js
                </a>
            </h1>
            <h1 className={styles.subtitle}>
                Desktop UI
            </h1>
            <p className={styles.description}>
                Get started by editing desktop 
                component in
                <code className={styles.code}>
                    pages/index.js
                </code>
            </p>
        </div>
    );
}

Steps to run the application: To run the app, type the following command in the terminal.

npm run dev

Output: Now open your browser and go to http://localhost:3000/, you will see the following output.


Next Article

Similar Reads