How to use the useMediaQuery hook for responsive design in Next.js



Image not found!!


To implement responsive design in Next.js using the useMediaQuery hook, you can use a library like @react-hook/media-query that provides a simple and efficient way to handle media queries in React applications. Here's a step-by-step guide on how to set it up:

  1. Install the required package:

    bash
    npm install @react-hook/media-query
  2. Create a custom hook for media queries:

    Create a new file, for example, useResponsive.js:

    jsx
    import { useMediaQuery } from '@react-hook/media-query'; const useResponsive = () => { const isSmallScreen = useMediaQuery('(max-width: 600px)'); const isMediumScreen = useMediaQuery('(min-width: 601px) and (max-width: 1200px)'); const isLargeScreen = useMediaQuery('(min-width: 1201px)'); return { isSmallScreen, isMediumScreen, isLargeScreen }; }; export default useResponsive;

    Adjust the media queries according to your design requirements.

  3. Use the custom hook in your components:

    jsx
    import React from 'react'; import useResponsive from '../path/to/useResponsive'; const YourComponent = () => { const { isSmallScreen, isMediumScreen, isLargeScreen } = useResponsive(); return ( <div> {isSmallScreen && <p>This is a small screen.</p>} {isMediumScreen && <p>This is a medium screen.</p>} {isLargeScreen && <p>This is a large screen.</p>} </div> ); }; export default YourComponent;

    Import the useResponsive hook and use the responsive booleans in your components to conditionally render content based on the screen size.

  4. Make your components responsive:

    Adjust your component styles or layout logic based on the responsive booleans returned by the useResponsive hook.

That's it! Now your Next.js application should be responsive, and components will adapt to different screen sizes. Adjust the media queries and styling logic based on your specific design requirements.