diff options
author | 2024-09-11 23:15:22 +0100 | |
---|---|---|
committer | 2024-09-11 23:15:22 +0100 | |
commit | 4123687310c1788c5b1ff85be920e42ab24d1d96 (patch) | |
tree | 395fd368f423eae47d5205053fe4efc743322c4f | |
parent | Wrap voucher in a card (diff) |
Add useMediaQuery hook
-rw-r--r-- | thallium-frontend/src/utils/hooks.ts | 22 |
1 files changed, 21 insertions, 1 deletions
diff --git a/thallium-frontend/src/utils/hooks.ts b/thallium-frontend/src/utils/hooks.ts index a98cfb3..73cd814 100644 --- a/thallium-frontend/src/utils/hooks.ts +++ b/thallium-frontend/src/utils/hooks.ts @@ -1,4 +1,4 @@ -import { useState, useEffect } from "react"; +import { useState, useEffect, useMemo } from "react"; import { type RefObject } from "react"; export function useVisible(ref: RefObject<HTMLElement>) { @@ -17,3 +17,23 @@ export function useVisible(ref: RefObject<HTMLElement>) { return isVisible; } + +export function useMediaQuery(query: string) { + const queryObject = useMemo(() => { + return window.matchMedia(query); + }, [query]); + + const [matches, setMatches] = useState(queryObject.matches); + + useEffect(() => { + const listenHook = (e: MediaQueryListEvent) => { + setMatches(e.matches); + } + + queryObject.addEventListener("change", listenHook); + + return () => queryObject.removeEventListener("change", listenHook); + }, [queryObject]); + + return matches; +} |