Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

react-tw-breakpoints

useBreakpoint hooks and tw-based components.

react, tailwind, tailwind4, breakpoints

readme

assets/project.svg

useBreakpoint hooks and tw-based components

Optimized SSR-friendly React hooks to get the current breakpoint based on:

  • Viewport: uses matchMedia and is global to window.
  • Container (true per-element): uses ResizeObserver to measure an element and return its breakpoint.

Includes condition helpers (largerThan/lessThan/onlyAt) and is tree-shakeable.

Installation

npm install react-tw-breakpoints

Peer deps: React 18/19 (DOM). Tailwind is NOT required for the hooks. If you use the experimental UI components (Container, Grid), Tailwind CSS is required and you must configure a safelist so their dynamic classes are included. See docs/guides/tailwind-safelist.md.

Documentation

Breakpoints

The library uses Tailwind-aligned breakpoints: xs (0px), sm (640px), md (768px), lg (1024px), xl (1280px), _2xl (1536px), and more.

Note:

  • Hook/constant identifiers use a leading underscore for sizes starting with a number (e.g. _2xl, _3xl) because TypeScript identifiers cannot start with digits. See BreakpointEnum.
  • Tailwind class names and component props use the native Tailwind form without underscore (e.g. 2xl). See Grid.

Scopes:

Quick start

1) Viewport

import { useBreakpoint, useBreakpointCondition } from 'react-tw-breakpoints';

function Example() {
  const bp = useBreakpoint(); // 'xs' | 'sm' | ...
  const isLgUp = useBreakpointCondition({ largerThan: 'lg' });
  const onlyMd = useBreakpointCondition({ onlyAt: 'md' });
  return (
    <div>
      <p>Viewport BP: {bp}</p>
      {isLgUp && <span>≥ lg</span>}
      {onlyMd && <span>md only</span>}
    </div>
  );
}

2) Container (true per-element)

import { useRef } from 'react';
import { useContainerBreakpoint } from 'react-tw-breakpoints';

function Card() {
  const ref = useRef<HTMLDivElement>(null);
  const bp = useContainerBreakpoint(ref); // based on the element width
  return (
    <div ref={ref} style={{ width: '100%' }}>
      {bp === 'xs' && <OneCol />}
      {bp === 'md' && <TwoCols />}
      {bp === 'lg' && <ThreeCols />}
    </div>
  );
}

API Overview

Hooks

useBreakpoint() - Returns the active viewport breakpoint label.

useBreakpointCondition(opts) - Evaluates viewport conditions (largerThan, lessThan, onlyAt).

useBreakpointContainer() - Container breakpoint set (viewport-based).

useContainerBreakpoint(ref) - True per-element breakpoint using ResizeObserver.

Helper Hooks: useBreakpointUp, useBreakpointDown, useBreakpointOnly, useBreakpointBetween

Hooks API Reference

Helpers

getCurrentBreakpoint() - Synchronously get current breakpoint (SSR-safe).

getMediaQuery(query) - Get cached MediaQueryList for custom queries.

Helpers API Reference

Components (Experimental)

[!CAUTION] These components are experimental and may change their API or functionality. They are subject to discussion and improvement proposals, so breaking changes or even removal may occur. Use them at your own risk.

There are some basic layout components to use in your application. These are independent of the hooks in this library, so they are not affected by changes to the API for hooks, helpers, etc.

Why?

Many UI libraries don't have basic layout components. You probably need something simple and straightforward like a <Container>, and you may not want to have to define it in every project you work on if you use the same UI library or another one that doesn't have one.

  • Container - Centered wrapper with max-width constraints.

  • Grid - 12-column responsive grid system.

Components API Reference

Quick Examples

Responsive Navigation

import { useBreakpointCondition } from 'react-tw-breakpoints';

function Navigation() {
  const isMobile = useBreakpointCondition({ lessThan: 'lg' });

  return <nav>{isMobile ? <MobileMenu /> : <DesktopMenu />}</nav>;
}

Adaptive Card

import { useRef } from 'react';
import { useContainerBreakpoint } from 'react-tw-breakpoints';

function Card() {
  const cardRef = useRef<HTMLDivElement>(null);
  const breakpoint = useContainerBreakpoint(cardRef);

  return (
    <div ref={cardRef}>
      {breakpoint === 'xs' && <CompactLayout />}
      {breakpoint === 'lg' && <ExpandedLayout />}
    </div>
  );
}

📚 More Examples

Advanced Topics

CSS @container Queries

For style-based container queries without JavaScript, use native CSS @container. Learn more.

SSR and StrictMode

Hooks use useSyncExternalStore for safe subscriptions. In SSR they return base values (xs or false) and hydrate on the client. No duplicate listeners in StrictMode.

Browser Compatibility

  • matchMedia: All modern browsers
  • ResizeObserver: Chrome/Edge 64+, Safari 13.1+, Firefox 69+
  • CSS @container: Chrome/Edge 105+, Safari 16+, Firefox 110+

FAQ

  • Why two kinds of “container breakpoints”?

    • useBreakpointContainer uses viewport with a different label set (useful if you want two global grids).
    • useContainerBreakpoint is true per element.
  • Can I change breakpoints?

    • Yes, edit src/const/breakpoints.ts and rebuild the package.
  • Tree‑shaking?

    • Yes. package.json exports ESM with sideEffects: false. Import only what you use.

Want to contribute?

Please read the contribution guidelines first.

License

MIT

changelog

Changelog

All notable changes to react-tw-breakpoints will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

[1.2.9] - 2025-10-30

Added

  • Comprehensive test suite for media query store multiple changes in src/__tests__/mediaQueryStore.multipleChanges.test.ts
  • Internal testing utilities (__internal__.clearAllListeners()) for proper test cleanup

Fixed

  • Critical bug in mediaQueryStore where listeners were only triggered on first media query change
  • Media query handlers now use stable references per query to ensure multiple consecutive changes trigger correctly
  • Query-specific event listeners now properly maintained in queryHandlers map
  • Memory leaks fixed with proper cleanup of handlers when unsubscribing
  • useBreakpointCondition now correctly triggers re-renders on all media query changes, not just the first one

[1.2.8] - 2025-10-22

Added

  • Export StaticBreakpointContainer and component props for external use
  • useBreakpoint helper hooks and comprehensive tests
  • ESLint and Prettier configuration for code quality
  • VSCode settings for Prettier formatting integration
  • Guidelines for code changes and file management in CONTRIBUTING.md
  • SSR-safe documentation for media query utilities
  • Deep package documentation

Changed

  • Refactored media query and breakpoint logic for better performance and maintainability
  • Renamed hooks to kebab-case convention and updated imports
  • Updated linting and formatting configuration
  • Refactored entire codebase to use consistent single quotes
  • Refactored tests to use single quotes and consistent formatting
  • Reformatted Vitest configuration and setup files
  • Updated npm scripts for improved testing and publishing workflows
  • Refactored npm publish workflow with integrated lint and test jobs
  • Updated code examples in documentation to use single quotes

Fixed

  • Warning block formatting in CONTRIBUTING.md

[1.2.4] - 2025-10-22

Added

  • Vitest configuration and setup files for testing environment
  • Comprehensive testing documentation in TESTING.md
  • Full test suite in src/__tests__/:
    • Unit tests
    • Hook tests
    • Component tests
  • Vitest and Testing Library dependencies in package.json

Changed

  • Updated package.json with Vitest and Testing Library dependencies
  • Updated package-lock.json to reflect new testing dependencies

[1.2.3] - 2025-10-20

Added

  • Project SVG asset (project.svg) with branded visual identity
  • SSR utility functions for environment checks
  • Comprehensive project documentation:
    • AGENTS.md for code style and SSR guidelines
    • CODE_OF_CONDUCT.md
    • CONTRIBUTING.md
    • LICENSE
  • JSDoc comments for improved code documentation
  • Publishing workflow configuration

Changed

  • Revamped project.svg with new color scheme and filters
  • Refactored SSR checks to use ssr-utils helpers
  • Updated README.md with project badges, contribution instructions, and license information
  • Improved code documentation and clarity

Removed

  • .npmignore file (optimized package distribution)

[1.0.1] - 2025-09-13

Added

  • Container and Grid components for responsive layouts
  • Container breakpoint hook for detecting component container breakpoints
  • Resize observer store for tracking element size changes
  • VSCode tasks for building the package

Changed

  • Refactored breakpoints hooks to use mediaQueryStore for better state management

[1.0.0] - 2025-09-06

Added

  • Initial breakpoints and hooks implementation
  • Core functionality for Tailwind CSS breakpoint detection and management