useWindowSize Hook

June 12, 2023

React Hooks

useWindowSize Hook

Thuta Sann

Thuta Sann

useWindowSize Hook to detect the Window Size


Share This Snippet To :

useLongPress Hook

In this section, I will demonstrate about the useWindowSize Hook that will be used for the detecting the Window Size

import React, { useEffect, useState } from 'react'; interface IWindow { width: number | undefined; height: number | undefined; } const useWindowSize = () => { const [windowSize, setWindowSize] = useState<IWindow>({ width: undefined, height: undefined, }); useEffect(() => { const handleResize = () => { setWindowSize({ width: window.innerWidth, height: window.innerHeight, }); }; window.addEventListener('resize', handleResize); handleResize(); return () => { window.removeEventListener('resize', handleResize); }; }, []); return windowSize; }; export default useWindowSize; // Usage const { width, height } = useWindowSize();

Cookie

I baked some cookies that you have to accept, if you want to enjoy my portfolio.
In order to gather information and make improvements, I should use some third-party cookies too, Can I?