How to get screen size detection in Next.js 13

How to get screen size detection in Next.js 13

The useMediaQuery hook is a powerful tool that can be used to make your Next.js app more responsive and user-friendly. It allows you to check for specific screen sizes and render different UI components depending on the device that the user is using.

Here i made a simple hook for screen detection in Next.js 13:

The useMediaQuery hook is a powerful tool that can be used to make your Next.js app more responsive and user-friendly. It allows you to check for specific screen sizes and render different UI components depending on the device that the user is using.

To use,

  1. First create a file useCustomScreenSize.js in app directory with folder utils
  2. Then, Copy and paste this code into the useCustomScreenSize.js
// Import the necessary React hooks
import { useCallback, useEffect, useState } from 'react';

// Define the `useMediaQuery` hook
const useMediaQuery = (width) => {
  // Create a state variable to track whether the target screen size has been reached
  const [targetReached, setTargetReached] = useState(false);

  // Define a callback function to be called when the media query matches or mismatches
  const updateTarget = useCallback((e) => {
    if (e.matches) {
      // If the media query matches, set the state variable to true
      setTargetReached(true);
    } else {
      // If the media query mismatches, set the state variable to false
      setTargetReached(false);
    }
  }, []);

  // Use the `useEffect` hook to listen for changes to the media query
  useEffect(() => {
    // Create a new media query object with the specified width
    const media = window.matchMedia(`(max-width: ${width}px)`);

    // Add a listener to the media query object for changes
    media.addListener(updateTarget);

    // Check the media query object on mount to see if it already matches
    if (media.matches) {
      // If the media query matches on mount, set the state variable to true
      setTargetReached(true);
    }

    // Return a function to remove the listener from the media query object
    return () => media.removeListener(updateTarget);
  }, []);

  // Return the state variable
  return targetReached;
};

// Export the hook
export default useMediaQuery;

3. To use the useMediaQuery hook, you would simply import it into your component and call it with the width of the screen size that you want to check for.

For example, the following code would check if the current screen size is below 768px:

import useMediaQuery from './useMediaQuery';

const MyComponent = () => {
  const isSmallScreen = useMediaQuery(768);

  // Render different UI components depending on whether the screen size is small or large
  if (isSmallScreen) {
    return <SmallScreenComponent />;
  } else {
    return <LargeScreenComponent />;
  }
};

Or you can use it wherever you want for example


import useMediaQuery from './useMediaQuery';

const IndexPage = () => {
  const sizes = useMediaQuery(768);

  return (
    <div>
      {sizes ? (
        <div>No sidebar</div>
      ) : (
        <div>
          <aside>Sidebar</aside>
          <main>Content</main>
        </div>
      )}
    </div>
  );
};

export default IndexPage;

This code will render the "No sidebar" text if the screen size is at least 768px, and a sidebar and main content area if the screen size is below 768px.

Happy Coding!

# Details

Published on January 31, 2024 3 min read

Next JS