typescriptbeginner

useBreakpoints Hook

Returns the current Tailwind-style breakpoint based on window width for responsive logic.

typescript
import { useState, useEffect } from 'react';

type Breakpoint = 'sm' | 'md' | 'lg' | 'xl' | '2xl';

const BREAKPOINTS: [Breakpoint, number][] = [
  ['2xl', 1536],
  ['xl', 1280],
  ['lg', 1024],
  ['md', 768],
  ['sm', 640],
];

export function useBreakpoint(): Breakpoint | null {
  const [breakpoint, setBreakpoint] = useState<Breakpoint | null>(null);

  useEffect(() => {
    const update = () => {
      const width = window.innerWidth;
      const match = BREAKPOINTS.find(([, minWidth]) => width >= minWidth);
      setBreakpoint(match ? match[0] : null);
    };

    update();
    window.addEventListener('resize', update);
    return () => window.removeEventListener('resize', update);
  }, []);

  return breakpoint;
}

// Usage:
// const bp = useBreakpoint();
// const isMobile = bp === 'sm' || bp === null;

Use Cases

  • Responsive component logic
  • Conditional rendering by screen size

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.