Certainly! Below is a TypeScript implementation of a custom React hook named useTailwindBreakpoint tailored for Next.js applications. This hook determines the current screen size and maps it to TailwindCSS breakpoint labels such as "xs", "sm", "md", etc. It listens for window resize events to ensure responsiveness.
TailwindCSS Default Breakpoints
By default, TailwindCSS defines the following breakpoints:
sm: 640px
md: 768px
lg: 1024px
xl: 1280px
2xl: 1536px
For the purpose of this hook, we'll add an "xs" breakpoint for screen widths below 640px.
Custom Hook: useTailwindBreakpoint
import { useState, useEffect } from 'react';
// Define the type for breakpoint names
type Breakpoint = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl';
// Define the TailwindCSS breakpoints in pixels
const breakpoints: Record<Breakpoint, number> = {
xs: 0, // Extra small screens
sm: 640, // Small screens
md: 768, // Medium screens
lg: 1024, // Large screens
xl: 1280, // Extra large screens
'2xl': 1536 // 2x extra large screens
};
// Utility function to determine the current breakpoint
const getBreakpoint = (width: number): Breakpoint => {
if (width >= breakpoints['2xl']) return '2xl';
if (width >= breakpoints.xl) return 'xl';
if (width >= breakpoints.lg) return 'lg';
if (width >= breakpoints.md) return 'md';
if (width >= breakpoints.sm) return 'sm';
return 'xs';
};
// Custom hook to get the current TailwindCSS breakpoint
const useTailwindBreakpoint = (): Breakpoint => {
const [breakpoint, setBreakpoint] = useState<Breakpoint>(() => {
if (typeof window !== 'undefined') {
return getBreakpoint(window.innerWidth);
}
// Default to 'xs' on server-side rendering
return 'xs';
});
useEffect(() => {
// Handler to call on window resize
const handleResize = () => {
const newBreakpoint = getBreakpoint(window.innerWidth);
setBreakpoint((prevBreakpoint) => {
if (prevBreakpoint !== newBreakpoint) {
return newBreakpoint;
}
return prevBreakpoint;
});
};
// Debounce the resize handler for performance
let timeoutId: NodeJS.Timeout;
const debouncedHandleResize = () => {
clearTimeout(timeoutId);
timeoutId = setTimeout(handleResize, 150);
};
window.addEventListener('resize', debouncedHandleResize);
// Call handler once to set initial breakpoint
handleResize();
// Cleanup event listener on unmount
return () => {
window.removeEventListener('resize', debouncedHandleResize);
clearTimeout(timeoutId);
};
}, []);
return breakpoint;
};
export default useTailwindBreakpoint;
Explanation
-
Breakpoint Definition: We define a Breakpoint type representing the possible breakpoint labels. The breakpoints object maps each breakpoint to its minimum width in pixels.
-
Determining Current Breakpoint: The getBreakpoint function takes the current window.innerWidth and returns the appropriate breakpoint label by comparing it against the defined breakpoints.
-
Initial State: The hook initializes the breakpoint state based on the current window width. If window is undefined (e.g., during server-side rendering in Next.js), it defaults to "xs".
-
Resize Listener: Using the useEffect hook, we add a window resize event listener. To optimize performance, the resize handler is debounced with a 150ms delay, preventing excessive state updates during rapid resize events.
-
Cleanup: The event listener and any pending timeouts are cleaned up when the component using the hook unmounts.
Usage Example
Here's how you can use the useTailwindBreakpoint hook within a Next.js component:
import React from 'react';
import useTailwindBreakpoint from '../hooks/useTailwindBreakpoint';
const ResponsiveComponent: React.FC = () => {
const breakpoint = useTailwindBreakpoint();
return (
<div className="p-4">
<p className="text-lg font-semibold">
Current Breakpoint: <span className="text-blue-500">{breakpoint}</span>
</p>
{/* Example: Render different content based on breakpoint */}
{breakpoint === 'xs' && <p>Extra Small Screen</p>}
{breakpoint === 'sm' && <p>Small Screen</p>}
{breakpoint === 'md' && <p>Medium Screen</p>}
{breakpoint === 'lg' && <p>Large Screen</p>}
{breakpoint === 'xl' && <p>Extra Large Screen</p>}
{breakpoint === '2xl' && <p>2X Extra Large Screen</p>}
</div>
);
};
export default ResponsiveComponent;
Considerations
-
Server-Side Rendering (SSR): Since Next.js performs server-side rendering, ensure that any logic accessing window is guarded to prevent reference errors. In the hook above, we default to "xs" when window is not available.
-
Customization: If you've customized TailwindCSS breakpoints in your tailwind.config.js, make sure to update the breakpoints object in the hook accordingly to match your configuration.
-
Performance: The debounce delay (150ms in the example) can be adjusted based on your application's responsiveness requirements. A shorter delay makes the UI more responsive to size changes but may introduce more function calls, whereas a longer delay reduces the number of updates but may make the UI feel less responsive.
-
Extensibility: You can enhance the hook to return more detailed information, such as the exact width or height, or to handle different orientations.
TailwindCSS Configuration
If you haven't customized your TailwindCSS breakpoints and are using the default configuration, the above hook will work seamlessly. However, if your project uses custom breakpoints, adjust the breakpoints object accordingly. Here's an example of customizing breakpoints in tailwind.config.js:
// tailwind.config.js
module.exports = {
theme: {
extend: {
screens: {
xs: '480px', // Example of a custom 'xs' breakpoint
// Override or add other breakpoints as needed
},
},
},
// ... other configurations
};
After customizing, ensure that the breakpoints in your hook mirror these custom values to maintain consistency across your application.
Conclusion
The useTailwindBreakpoint hook provides a straightforward way to access the current TailwindCSS breakpoint within your React components, enabling responsive design logic in your JavaScript or TypeScript code. By integrating this hook into your Next.js project, you can create components that adapt not only through CSS but also through conditional rendering and behavior based on the screen size.