Shadcn Hooks

useIsMatchMedia

A hook to check if the media query matches

Loading...

Installation

npx shadcn@latest add @hooks/use-is-match-media
pnpm dlx shadcn@latest add @hooks/use-is-match-media
yarn dlx shadcn@latest add @hooks/use-is-match-media
bun x shadcn@latest add @hooks/use-is-match-media

Copy and paste the following code into your project.

use-isomorphic-layout-effect.ts
import { useEffect, useLayoutEffect } from 'react'
import { isBrowser } from '@/registry/lib/is-browser'

/**
 * Custom hook that uses either `useLayoutEffect` or `useEffect` based on the environment (client-side or server-side).
 * @param {Function} effect - The effect function to be executed.
 * @param {Array<any>} [dependencies] - An array of dependencies for the effect (optional).
 * @public
 * @see [Documentation](https://usehooks-ts.com/react-hook/use-isomorphic-layout-effect)
 * @example
 * ```tsx
 * useIsomorphicLayoutEffect(() => {
 *   // Code to be executed during the layout phase on the client side
 * }, [dependency1, dependency2]);
 * ```
 */
export const useIsomorphicLayoutEffect = isBrowser ? useLayoutEffect : useEffect

use-is-match-media.ts
import { useState } from 'react'
import { useIsomorphicLayoutEffect } from '@/registry/hooks/use-isomorphic-layout-effect'

export function useIsMatchMedia(mediaQueryString: string) {
  const [isMatch, setIsMatch] = useState(() => {
    if (typeof window === 'undefined') return false
    return window.matchMedia(mediaQueryString).matches
  })

  useIsomorphicLayoutEffect(() => {
    const mediaQueryList = window.matchMedia(mediaQueryString)

    setIsMatch(mediaQueryList.matches)

    const listener = (event: MediaQueryListEvent) => {
      setIsMatch(event.matches)
    }

    mediaQueryList.addEventListener('change', listener)

    return () => {
      mediaQueryList.removeEventListener('change', listener)
    }
  }, [mediaQueryString])

  return isMatch
}

API

/**
 * A hook to check if the media query matches
 * @param mediaQueryString - The media query string to check
 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia#mediaquerystring
 * @returns A boolean indicating if the media query matches
 */
export function useIsMatchMedia(mediaQueryString: string): boolean

Credits

Last updated on