React Custom Hook: useMediaQuery

React Custom Hook: useMediaQuery
React Custom Hook: useMediaQuery

In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the "useMediaQuery" hook, one of the many carefully crafted hooks available in the collection of React custom hooks.

import { useState, useEffect } from "react" import useEventListener from "../useEventListener/useEventListener" export default function useMediaQuery(mediaQuery) { const [isMatch, setIsMatch] = useState(false) const [mediaQueryList, setMediaQueryList] = useState(null) useEffect(() => { const list = window.matchMedia(mediaQuery) setMediaQueryList(list) setIsMatch(list.matches) }, [mediaQuery]) useEventListener("change", e => setIsMatch(e.matches), mediaQueryList) return isMatch }

The useMediaQuery hook allows you to dynamically update your UI based on a given media query. Simply pass in the desired media query as a parameter, and the hook will return a boolean value indicating whether the media query matches the current viewport size.

One of the key advantages of this custom hook is its simplicity and reusability. With just a few lines of code, you can effortlessly implement responsive behavior throughout your application. Whether you need to conditionally render components, apply specific styles, or trigger different functionality based on screen size, useMediaQuery has got you covered.

import useMediaQuery from "./useMediaQuery" export default function MediaQueryComponent() { const isLarge = useMediaQuery("(min-width: 200px)") return <div>Large: {isLarge.toString()}</div> }

This hook is not limited to specific use cases; it can be utilized in a variety of scenarios. For instance, you can use it to dynamically adjust the layout of a navigation menu, hide or show certain elements based on screen size, or even optimize the loading of data based on the available space. The possibilities are endless, and the useMediaQuery hook empowers you to deliver a seamless user experience across different devices and screen sizes.

11
Начать дискуссию