Skip to content

Instantly share code, notes, and snippets.

@sairajchouhan
Created February 6, 2022 13:12
Show Gist options
  • Save sairajchouhan/a814aa552b6eb75a401637682233134a to your computer and use it in GitHub Desktop.
Save sairajchouhan/a814aa552b6eb75a401637682233134a to your computer and use it in GitHub Desktop.
I use this buddy in every tailwind project so thought to put it here so that I don't have to bang my head writing the same hook again and again
import { useEffect, useState } from 'react'
export type ScreenSize = 'sm' | 'md' | 'lg' | 'xl' | '2xl' | '_'
export const getScreenSize = (width: number) => {
let screenSize: ScreenSize = '_'
if (width < 768 && width >= 640) {
screenSize = 'sm'
}
if (width < 1024 && width >= 768) {
screenSize = 'md'
}
if (width < 1280 && width >= 1024) {
screenSize = 'lg'
}
if (width < 1536 && width >= 1280) {
screenSize = 'xl'
}
if (width >= 1536) {
screenSize = '2xl'
}
return screenSize
}
const useWindowSize = () => {
const [screenSize, setScreenSize] = useState<ScreenSize>(() => {
if (typeof window !== 'undefined') {
return getScreenSize(window.innerWidth)
} else {
return '_'
}
})
useEffect(() => {
const resizeCallBack = (e: any) => {
const width = e.target.outerWidth
setScreenSize(getScreenSize(width))
}
window.addEventListener('resize', resizeCallBack)
return () => {
window.removeEventListener('resize', resizeCallBack)
}
}, [])
return { screenSize }
}
export default useWindowSize
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment