Create a Custom Hook to Make Next.js Apps Responsive
Last Updated :
25 Jul, 2024
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.
Similar Reads
How to Create a New Next JS 13+ App? Creating a new Next.js 13+ application is a straightforward process that sets up a modern React-based framework with built-in features like server-side rendering, static site generation, and API routes. Next JS streamlines and automates the setup of essential React tooling, handling tasks such as bu
2 min read
How To Create A Custom Image Loader In NextJS? Creating a custom image loader in Next.js allows you to control how images are loaded and optimized. This is useful for integrating with different image services or handling specific image processing needs. Hereâs how to create and use a custom image loader: This article will walk you through the st
4 min read
Next.js Create Next App In Next.js, the create next app command is used to automatically initialize a new NextJS project with the default configuration, providing a streamlined way to build applications efficiently and quickly.System Requirements:Node.js 12.22.0 or laterNPM 6.14.4 or later OR Yarn 1.22.10 or latermacOS, Wi
3 min read
Create Hero Sections using Next.JS and Tailwind CSS We will learn how to create a beautiful Hero Section using Next.js and Tailwind CSS. A Hero Section is the first visual element a user sees on a website and it is very important for making a good first impression. It contains a bold headline, a call to action (CTA), and sometimes an image or video.
3 min read
How to Catch All Routes in Next.js ? To catch all routes in Next.js, you create a dynamic route file using the catch-all segments syntax. This allows you to handle various routes dynamically, enhancing routing flexibility and application structure.Catch all routesTo catch all routes in next js, We willCreate a file named [...gfg].js in
2 min read