Random Access Components

use-breakpoints

Utility hook to define breakpoints given the screen size

Demo

Current Breakpoints
Mobile Size
Tablet Size
Desktop Size

Resize your browser window to see the values update in real-time

import { useBreakPoints } from "@/hooks/use-breakpoints";
import { cn } from "@/lib/utils";

const UseBreakpointsDemo: React.FC = () => {
  
    const { isMobile, isTablet, isDesktop } = useBreakPoints();

  return (
    <div className="text-center space-y-4">
        <div className="text-lg font-semibold text-foreground">
          Current Breakpoints
        </div>
        <div className="flex gap-4 w-full items-center justify-center">
          <div className={cn("bg-muted/50 rounded-lg p-4", isMobile && "bg-primary/20")}>
            <div className={"text-base font-bold text-foreground whitespace-nowrap"}>
            Mobile Size
            </div>
          </div>
          <div className={cn("bg-muted/50 rounded-lg p-4", isTablet && "bg-primary/20")}>
            <div className="text-base font-bold text-foreground whitespace-nowrap">
              Tablet Size
            </div>
          </div>
          <div className={cn("bg-muted/50 rounded-lg p-4", isDesktop && "bg-primary/20")}>
            <div className="text-base font-bold text-foreground whitespace-nowrap">
              Desktop Size
            </div>
          </div>
        </div>
        <p className="text-sm text-muted-foreground">
          Resize your browser window to see the values update in real-time
        </p>
    </div>
  );
};

export { UseBreakpointsDemo };

Installation

This hook is based on the use-screen-size hook.

Copy and paste the following code into your project.

use-breakpoints.ts
import useScreenSize from "@/hooks/use-screen-size";

const MOBILE_WIDTH = 768;
const TABLET_WIDTH = 1024;

export type BreakPoints = {
    isMobile: boolean;
    isTablet: boolean;
    isDesktop: boolean;
}

export const useBreakPoints = (): BreakPoints => {

    const { width } = useScreenSize();
    
    const isMobile = width < MOBILE_WIDTH;
    const isTablet = width >= MOBILE_WIDTH && width < TABLET_WIDTH;
    const isDesktop = width >= TABLET_WIDTH;

    return { isMobile, isTablet, isDesktop };
}

Usage

import { useBreakPoints } from "@/hooks/use-breakpoints";
const { isMobile, isTablet, isDesktop } = useBreakPoints();

On this page