The Hook
import { useState } from 'react'
// See: https://usehooks-ts.com/react-hook/use-event-listener
import { useEventListener } from '../useEventListener'
// See: https://usehooks-ts.com/react-hook/use-isomorphic-layout-effect
import { useIsomorphicLayoutEffect } from '../useIsomorphicLayoutEffect'
interface WindowSize {
width: number
height: number
}
function useWindowSize(): WindowSize {
const [windowSize, setWindowSize] = useState<WindowSize>({
width: 0,
height: 0,
})
const handleSize = () => {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
})
}
useEventListener('resize', handleSize)
// Set size at the first client-side load
useIsomorphicLayoutEffect(() => {
handleSize()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
return windowSize
}
export default useWindowSize
usage
import React from 'react'
import { useWindowSize } from 'usehooks-ts'
export default function Component() {
const { width, height } = useWindowSize()
return (
<div>
The current window dimensions are:{' '}
<code>{JSON.stringify({ width, height })}</code>
</div>
)
}
'React.js' 카테고리의 다른 글
[React] 화면 특정 위치로 포커싱하기 (0) | 2022.05.19 |
---|---|
[React] 특정 영역 안에서 무한 스크롤 (0) | 2022.05.16 |
[React] Amazone s3 임시 파일 저장 및 URL 가져오기 (0) | 2022.05.11 |
[React] typescript IntrinsicAttributes error (0) | 2022.05.09 |
[React] selectBox 직접 구현하기 (0) | 2022.04.26 |