-
React) 브라우저의 변하는 width, height를 Hook으로 전달받기Programing Language/React.js 2022. 6. 23. 14:18728x90반응형
import {useEffect, useState} from "react"; interface WindowSize { width: number height: number } const useWindowSizeCustom = (): WindowSize => { // Initialize state with undefined width/height so server and client renders match // Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/ const [windowSize, setWindowSize] = useState<WindowSize>({ width : 0, height: 0, }); useEffect(() => { // only execute all the code below in client side if (typeof window !== 'undefined') { const handleResize = () => { setWindowSize({ width: window.innerWidth, height: window.innerHeight, }); } // Add event listener window.addEventListener("resize", handleResize); // Call handler right away so state gets updated with initial window size handleResize(); // Remove event listener on cleanup return () => window.removeEventListener("resize", handleResize); } else { return () => window.removeEventListener("resize", () => { return null }); } }, []); // Empty array ensures that effect is only run on mount return windowSize; } export default useWindowSizeCustom;
개발자 코손실 방지를 위해 하단의 광고를 클릭해주세요!
728x90반응형'Programing Language > React.js' 카테고리의 다른 글
Recoil) Atom Effects에서 isReset 값 false 로 실행하기 (0) 2022.11.15 Recoil) Expectation Violation: Duplicate atom key "". This is a FATAL ERROR in 해결하기 (0) 2022.11.14 NextJS ) next js websocket.js?a9be:45 WebSocket connection to (0) 2022.09.29 React) Swiper 사용하기 (0) 2022.05.27 React.js) FilePond 다루기(파일 업로드 모듈) (0) 2022.05.05