Skip to content

Instantly share code, notes, and snippets.

@donaldpipowitch
Created September 11, 2019 12:52
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 donaldpipowitch/7f1e0c92db55518d841c131194c1d44f to your computer and use it in GitHub Desktop.
Save donaldpipowitch/7f1e0c92db55518d841c131194c1d44f to your computer and use it in GitHub Desktop.
useBreakpoints hook for React
import React, { createContext, useContext, useMemo, FC } from 'react';
import { useMedia } from 'use-media';
enum Breakpoints {
small = 'min-width: 768px',
medium = 'min-width: 992px',
large = 'min-width: 1200px'
}
type BreakpointsContextValue = {
isSmall: boolean;
isMedium: boolean;
isLarge: boolean;
};
const BreakpointsContext = createContext<BreakpointsContextValue>(null as any);
export function useBreakpoints() {
const context = useContext(BreakpointsContext);
if (!context)
throw new Error(
'The component you used uses the useBreakpoints hook which needs to be placed inside a BreakpointsProvider. Please wrap your component inside <BreakpointsProvider></BreakpointsProvider>.'
);
return context;
}
export const BreakpointsProvider: FC = ({ children }) => {
const isSmall = useMedia(Breakpoints.small);
const isMedium = useMedia(Breakpoints.medium);
const isLarge = useMedia(Breakpoints.large);
const value = useMemo(() => ({ isSmall, isMedium, isLarge }), [
isSmall,
isMedium,
isLarge
]);
return (
<BreakpointsContext.Provider value={value}>
{children}
</BreakpointsContext.Provider>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment