useMediaQuery
A hook for responsive design using media queries. This custom hook provides a way to adapt your components based on screen size and device characteristics.
Implementation
function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState(false);
useEffect(() => {
const media = window.matchMedia(query);
setMatches(media.matches);
const listener = (event: MediaQueryListEvent) => {
setMatches(event.matches);
};
media.addEventListener('change', listener);
return () => media.removeEventListener('change', listener);
}, [query]);
return matches;
}
Usage
Adapt layout based on screen size
export default function App() {
const isSmall = useMediaQuery('(max-width: 400px)');
const isMedium = useMediaQuery('(min-width: 401px) and (max-width: 800px)');
return (
<div style={{
padding: '20px',
textAlign: 'center'
}}>
<h3>Resize the window!</h3>
{isSmall && <p>👋 Hello mobile user!</p>}
{isMedium && <p>👨💻 Hello tablet user!</p>}
{!isSmall && !isMedium && <p>🖥️ Hello desktop user!</p>}
</div>
);
}
Parameters
querystringrequired
Media query string
Live Playground
Best Practices
- Use standard media query syntax
- Consider performance with multiple queries
- Combine with useCallback for event handlers
Performance
- Minimal overhead
- Efficient event listener management
- Automatic cleanup