useTailwindBreakpoint
A hook for observing breakpoints using Tailwind CSS breakpoints and custom media queries
Source Code
import theme from "tailwindcss/defaultTheme";
import { useMatchMedia } from "../use-match-media";
const breakpoints = theme?.screens as Record<string, string>;
type Breakpoint = keyof typeof breakpoints;
export const useTailwindBreakpoint = (breakpoint: Breakpoint) => {
const query = breakpoints[breakpoint];
return useMatchMedia(`(min-width: ${query})`);
};Features
- Tailwind Integration: Uses tailwindcss breakpoints from the default config
- SSR Compatible: Works seamlessly with server-side rendering
API Reference
useTailwindBreakpoint
| Prop | Default | Type | Description |
|---|---|---|---|
breakpoint | - | Breakpoint | The Tailwind CSS breakpoint to observe. |
Note: The actual available breakpoints depend on your Tailwind configuration. If you have custom screen tokens defined in your
theme, those will also be available.
Examples
Basic Usage
Mobile Device (≥640px)
Resize your browser to see the background change!
import { cn } from "@/lib/utils/classnames";
import { useTailwindBreakpoint } from "../use-tailwind-breakpoint";
export default function UseTailwindBreakpointPreview() {
const sm = useTailwindBreakpoint("sm");
const md = useTailwindBreakpoint("md");
const lg = useTailwindBreakpoint("lg");
const getBackgroundColor = () => {
if (lg) return "bg-green-500";
if (md) return "bg-yellow-500";
if (sm) return "bg-blue-500";
return "bg-red-500";
};
const getDeviceText = () => {
if (lg) return "Desktop Device (≥1024px)";
if (md) return "Tablet Device (≥768px)";
if (sm) return "Small Device (≥640px)";
return "Mobile Device (≥640px)";
};
return (
<div
className={cn(
"h-full w-full rounded-xl border border-border p-6 text-black transition-colors duration-300",
getBackgroundColor(),
)}
>
<div className="flex h-full items-center justify-center rounded-lg bg-white/50 p-4">
<div className="text-center">
<p className="font-semibold text-gray-800 text-lg">{getDeviceText()}</p>
<p className="mt-2 text-gray-600 text-sm">
Resize your browser to see the background change!
</p>
</div>
</div>
</div>
);
}Best Practices
-
Breakpoint Consistency:
- Use
useTailwindBreakpointwith Tailwind breakpoint names for consistency with your CSS
- Use
-
Separation of Concerns:
- Use Tailwind classes for visual responsive design
- Use the hook for JS logics, state management, and conditional rendering
Previous
useStableCallback
Next
useTicker