Skip to content

Instantly share code, notes, and snippets.

@adbutterfield
Last active July 10, 2020 02:23
Show Gist options
  • Save adbutterfield/bcb2ffae73bb6b8430de25aaca97d354 to your computer and use it in GitHub Desktop.
Save adbutterfield/bcb2ffae73bb6b8430de25aaca97d354 to your computer and use it in GitHub Desktop.
React hook for responsive fun
import { useState, useLayoutEffect } from 'react';
const useOnMobile = () => {
const [isMobile, setIsMobile] = useState(true);
const resizeCallback = () => {
if (window.innerWidth < 768) {
setIsMobile(true);
} else {
setIsMobile(false);
}
};
useLayoutEffect(() => {
if (window.innerWidth > 767) {
setIsMobile(false);
}
window.addEventListener('resize', resizeCallback);
return () => {
window.removeEventListener('resize', resizeCallback);
};
}, []);
return isMobile;
};
export default useOnMobile;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment