Skip to content

Instantly share code, notes, and snippets.

@i-havr
Last active September 5, 2023 06:35
Show Gist options
  • Save i-havr/45c5fb61ae948bd23671c4fbc40a60da to your computer and use it in GitHub Desktop.
Save i-havr/45c5fb61ae948bd23671c4fbc40a60da to your computer and use it in GitHub Desktop.
Custom React.js hook which returns the current width of the window. Also the current state of mobile/tablet/desktop screen is returned.
'use client';
import { useState, useEffect } from 'react';
// const SCREEN_MOBILE = 320;
const LARGE_SCREEN_MOBILE = 480;
const SCREEN_TABLET = 768;
const SCREEN_DESKTOP = 1280;
const LARGE_SCREEN_DESKTOP = 1440;
export const useWindowWidth = () => {
const [width, setWidth] = useState<number | null>(null);
useEffect(() => {
if (!width) {
setWidth(window.innerWidth);
}
const handleResize = (event: Event): void => {
if (event.target instanceof Window) {
setWidth(event.target.innerWidth);
}
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, [width]);
const isScreenMobile = width! < SCREEN_TABLET;
const isLargeScreenMobile =
width! >= LARGE_SCREEN_MOBILE && width! < SCREEN_TABLET;
const isScreenTablet = width! >= SCREEN_TABLET && width! < SCREEN_DESKTOP;
const isScreenDesktop = width! >= SCREEN_DESKTOP;
const isLargeScreenDesktop = width! >= LARGE_SCREEN_DESKTOP;
return {
width,
isScreenMobile,
isLargeScreenMobile,
isScreenTablet,
isScreenDesktop,
isLargeScreenDesktop,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment