Skip to content

Instantly share code, notes, and snippets.

@YussufElarif
Created November 6, 2020 13:17
Show Gist options
  • Save YussufElarif/da787c2a88035e1e06dd5fe400df46ec to your computer and use it in GitHub Desktop.
Save YussufElarif/da787c2a88035e1e06dd5fe400df46ec to your computer and use it in GitHub Desktop.
React Responsive Hook
import { useState, useEffect } from 'react';
export enum DeviceEnum
{
Desktop,
Tablet,
Mobile
}
export function useDevice()
{
const [device, setDevice] = useState<DeviceEnum>();
useEffect(() =>
{
handleResize();
}, []);
useEffect(() =>
{
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
function handleResize()
{
// If width greater than tablet
if (window.innerWidth > 979)
{
return setDevice(DeviceEnum.Desktop);
}
// If width greater than mobile
if (window.innerWidth > 500)
{
return setDevice(DeviceEnum.Tablet);
}
return setDevice(DeviceEnum.Mobile);
}
return {
desktop: device === DeviceEnum.Desktop,
tablet: device === DeviceEnum.Tablet,
mobile: device === DeviceEnum.Mobile
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment