Hook API: useBreakpoint
See original GitHub issueI propose a hooks API:
import { up, useBreakpoint } from 'styled-breakpoints`
const isMobile = useBreakpoint(up('tablet'));
Working Implementation:
import { useState, useEffect } from 'react';
import { useTheme } from 'styled-components';
export const useBreakpoint = (breakpoint: (z: { theme: any }) => string) => {
const theme = useTheme();
const query = breakpoint({ theme }).replace(/^@media/, '');
const mq = window.matchMedia(query);
const [isBreak, setIsBreak] = useState(mq.matches);
useEffect(() => {
function handleResize() {
setIsBreak(window.matchMedia(query).matches);
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return isBreak;
};
export default useBreakpoint;
Issue Analytics
- State:
- Created 3 years ago
- Reactions:3
- Comments:7 (4 by maintainers)
Top Results From Across the Web
iiroj/use-breakpoint: A React hook for getting the ... - GitHub
For a list of breakpoints, we generate some css media queries in the form of (min-width: XXXpx) and (max-width: YYYpx) and then add...
Read more >useBreakpoint - React Hook - DEV Community
The useBreakpoint hook will return one of the breakpoints based on the device width. The below table would help determine the breakpoints for ......
Read more >use-breakpoint - npm
A React hook for getting the current responsive media breakpoint. Latest version: 3.0.6, last published: 21 days ago.
Read more >Custom hooks to use breakpoints for React
Similar to pmndrs/zustand 's create API, initialize the breakpoint hooks ... export const { useBreakpoint } = create(config.theme.screens); ...
Read more >restart/hooks
API. useAnimationFrame · useBreakpoint · useCallbackRef · useCommittedRef · useCustomEffect ... @restart/hooks is a utility library of React hooks.
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Maybe something like:
The benefit would be to be able to not render both and keep one hidden. This would require some sort of window resize handler to trigger updates.
I created the hook to use the same breakpoints defined in my theme in my component’s logic, specifically to enable and disable certain animations using react-spring that are only relevant on mobile layouts. There’s a lot of one could do with this hook and I imagine a lot of problems can be solved with this hook.