Reactで画面サイズを取得するHooks

Reactにおいて画面サイズを取得するためのCustom Hooks

import { useState, useEffect } from 'react';

export const useWindowDimensions = () => {

  const getWindowDimensions = () => {
    const { innerWidth: width, innerHeight: height } = window;
    return {
      width,
      height
    };
  }

  const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());
  useEffect(() => {
    const onResize = () => {
      setWindowDimensions(getWindowDimensions());
    }
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);
  return windowDimensions;
}

SSRでおこないたい場合

export const useWindowDimensions = () => {
  const isClient = typeof window === 'object';
  const getWindowDimensions = useCallback(() => {
    return {
      width: isClient ? window?.innerWidth : 0,
      height: isClient ? window?.innerHeight : 0
    };
  }, [isClient]);
  const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());
  useEffect(() => {
    const onResize = () => {
      setWindowDimensions(getWindowDimensions());
    };
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, [getWindowDimensions]);
  return windowDimensions;
};

使うとき

const App = () => {
    const { width, height } = useWindowDimensions();
    console.log(width);
    console.log(height);
    return (<></>);
}

関連記事