Component Navigation
Code/React Hooks/useScreenSize

useScreenSize

A custom React hook that returns the current viewport width in px, as well as the current screensize category ('base' | 'sm' | 'md' | 'lg' | 'xl').

useScreenSize Hook

A custom React hook that returns the current viewport width in px, as well as the current screensize category ('base' | 'sm' | 'md' | 'lg' | 'xl').

ReactTypeScript
tsx
import { useEffect, useState } from 'react';

export type ScreenSize = 'base' | 'sm' | 'md' | 'lg' | 'xl';

function getScreenSize(width: number): ScreenSize {
  if (width < 512) return 'base';
  if (width < 768) return 'sm';
  if (width < 1024) return 'md';
  if (width < 1280) return 'lg';
  return 'xl';
}

export function useScreenSize(): ScreenSize {
  const [size, setSize] = useState<ScreenSize>(() => getScreenSize(window.innerWidth));

  useEffect(() => {
    const handleResize = () => {
      setSize(getScreenSize(window.innerWidth));
    };

    window.addEventListener('resize', handleResize);

    return () => window.removeEventListener('resize', handleResize);
  }, [setSize]);

  return size;
}