Skip to content

Instantly share code, notes, and snippets.

@manabuyasuda
Created January 30, 2025 10:17
Show Gist options
  • Save manabuyasuda/5af4af633b278c31a62f544a94def74b to your computer and use it in GitHub Desktop.
Save manabuyasuda/5af4af633b278c31a62f544a94def74b to your computer and use it in GitHub Desktop.
/**
* メディアクエリの一致状態を監視するカスタムフックです。
* @param mediaQuery メディアクエリ文字列(例: '(min-width: 768px)')
* @returns boolean - メディアクエリに一致する場合はtrue、それ以外はfalse
*/
export function useMediaQuery(mediaQuery: string): boolean {
// サーバーサイドでは初期値を`false`として、クライアントサイドでは結果を返す
const getInitialValue = () =>
typeof window !== 'undefined'
? window.matchMedia(mediaQuery).matches
: false;
const [matches, setMatches] = useState<boolean>(getInitialValue());
useEffect(() => {
// サーバーサイドでは実行しない
if (typeof window === 'undefined') return;
// MediaQueryListオブジェクトを作成する
const mediaQueryList = window.matchMedia(mediaQuery);
// メディアクエリの状態が変更された時のハンドラー
const updateMatches = () => {
setMatches(mediaQueryList.matches);
};
// メディアクエリが変更されたときに更新する
mediaQueryList.addEventListener('change', updateMatches);
// クリーンアップ関数
return () => {
mediaQueryList.removeEventListener('change', updateMatches);
};
}, [mediaQuery]);
return matches;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment