Certainly! Below is the implementation of the useScreenSize React hook in TypeScript, tailored to align with Tailwind CSS breakpoints. This hook listens for window resize events and returns the current screen size category ("base", "sm", "md", "lg", "xl", "2xl").
File: screen-size.hook.ts
import { useState, useEffect } from 'react';
// Define the possible screen size categories based on TailwindCSS breakpoints
export type ScreenSize = 'base' | 'sm' | 'md' | 'lg' | 'xl' | '2xl';
// TailwindCSS default breakpoints in pixels
const breakpoints: { [key in Exclude<ScreenSize, 'base'>]: number } = {
sm: 640,
md: 768,
lg: 1024,
xl: 1280,
'2xl': 1536,
};
/**
* Determines the current screen size category based on the window width.
* @param width - The current window width in pixels.
* @returns The corresponding ScreenSize category.
*/
const getScreenSize = (width: number): ScreenSize => {
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 'base';
};
/**
* Custom React hook to get the current screen size category based on TailwindCSS breakpoints.
* Listens to window resize events to update the screen size responsively.
*
* @returns The current ScreenSize category.
*/
export const useScreenSize = (): ScreenSize => {
// Initialize state with current screen size or 'base' if window is undefined (e.g., during SSR)
const [screenSize, setScreenSize] = useState<ScreenSize>(() => {
if (typeof window !== 'undefined') {
return getScreenSize(window.innerWidth);
}
return 'base';
});
useEffect(() => {
// Handler to call on window resize
const handleResize = () => {
const newSize = getScreenSize(window.innerWidth);
setScreenSize(newSize);
};
// Add event listener for window resize
window.addEventListener('resize', handleResize);
// Call handler once to set initial size
handleResize();
// Cleanup event listener on component unmount
return () => window.removeEventListener('resize', handleResize);
}, []);
return screenSize;
};
Explanation
-
Type Definition:
ScreenSize: A union type representing the possible screen size categories, including a base category for widths smaller than Tailwind's sm breakpoint.
-
Breakpoints:
- The
breakpoints object maps each Tailwind breakpoint (sm, md, lg, xl, 2xl) to its corresponding minimum width in pixels.
-
getScreenSize Function:
- This function takes the current window width and determines which screen size category it falls into by comparing it against the defined breakpoints.
- It checks from the largest breakpoint down to
sm, returning the appropriate category. If the width is smaller than the smallest breakpoint (sm), it returns base.
-
useScreenSize Hook:
- State Initialization:
- Initializes the
screenSize state with the current screen size. It checks if window is defined to ensure compatibility with Server-Side Rendering (SSR). If window is not available, it defaults to 'base'.
- Effect Hook:
- Sets up an event listener for the
resize event on the window object.
- The
handleResize function updates the screenSize state whenever the window is resized.
- It invokes
handleResize immediately to set the initial screen size.
- Cleans up the event listener when the component using the hook is unmounted to prevent memory leaks.
-
Export:
- The hook is exported for use in other parts of your Next.js application.
Usage Example
Here's how you can use the useScreenSize hook in a React component:
import React from 'react';
import { useScreenSize } from './screen-size.hook';
const ResponsiveComponent: React.FC = () => {
const screenSize = useScreenSize();
return (
<div>
<p>Current screen size: {screenSize}</p>
{screenSize === 'sm' && <p>Small screen content</p>}
{screenSize === 'md' && <p>Medium screen content</p>}
{/* Add more conditions based on your needs */}
</div>
);
};
export default ResponsiveComponent;
Additional Considerations
This implementation should seamlessly integrate with your Next.js project using TypeScript and TailwindCSS, providing responsive behavior based on screen size categories.