Skip to content

Instantly share code, notes, and snippets.

@santoshvijapure
Created December 5, 2022 02:50
Show Gist options
  • Save santoshvijapure/67da2111677dbc65a3fce41b7a122bf8 to your computer and use it in GitHub Desktop.
Save santoshvijapure/67da2111677dbc65a3fce41b7a122bf8 to your computer and use it in GitHub Desktop.
React hook to determine the client device based on the screen size
import { useLayoutEffect, useState } from 'react';
import debounce from 'lodash/debounce';
const useIsMobile = (): boolean => {
const [isMobile, setIsMobile] = useState(false);
useLayoutEffect(() => {
const updateSize = (): void => {
setIsMobile(window.innerWidth < 768);
};
window.addEventListener('resize', debounce(updateSize, 250));
// updateSize();
return (): void => window.removeEventListener('resize', updateSize);
}, []);
return isMobile;
};
export default useIsMobile;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment