Skip to content

Instantly share code, notes, and snippets.

@EvanAgee
Created March 11, 2021 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EvanAgee/73ab8f037f434809c18d0b768ac0ee4b to your computer and use it in GitHub Desktop.
Save EvanAgee/73ab8f037f434809c18d0b768ac0ee4b to your computer and use it in GitHub Desktop.
React breakpoint / responsive hook
/**
* Example:
* import useBreakpoint from './useBreakpoint'
*
* const MyComponent = () => {
* const breakpoint = useBreakpoint();
*
* {breakpoint.isMdUp && <AnotherComponent />}
* {breakpoint.xl && <AnotherComponent />}
* };
*/
import { useState, useEffect, useMemo } from 'react';
import throttle from 'lodash.throttle';
const breakpointValues = ['xs', 'sm', 'md', 'lg', 'xl'];
const getDeviceConfig = (width) => {
if (width < 576) {
return 0;
} else if (width >= 576 && width < 768) {
return 1;
} else if (width >= 768 && width < 992) {
return 2;
} else if (width >= 992 && width < 1200) {
return 3;
} else if (width >= 1200) {
return 4;
}
};
const useBreakpoint = () => {
const [brkPnt, setBrkPnt] = useState(() =>
getDeviceConfig(window.innerWidth)
);
useEffect(() => {
const calcInnerWidth = throttle(function () {
setBrkPnt(getDeviceConfig(window.innerWidth));
}, 200);
window.addEventListener('resize', calcInnerWidth);
return () => window.removeEventListener('resize', calcInnerWidth);
}, []);
const breakpoint = useMemo(() => {
return {
breakpoint: breakpointValues[brkPnt],
xs: brkPnt === 0,
sm: brkPnt === 1,
md: brkPnt === 2,
lg: brkPnt === 3,
xl: brkPnt === 4,
isSmUp: brkPnt >= 1,
isMdUp: brkPnt >= 2,
isLgUp: brkPnt >= 3,
isXlUp: brkPnt === 4,
isSmDown: brkPnt <= 1,
isMdDown: brkPnt <= 2,
isLgDown: brkPnt <= 3,
isXlDown: brkPnt <= 4,
}
}, [brkPnt]);
return breakpoint;
};
export default useBreakpoint;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment