Skip to content

Instantly share code, notes, and snippets.

@fmontone

fmontone/useWindowSize.js

Last active Mar 16, 2020
Embed
What would you like to do?
Custom React hook to get window size and return an object with width and height (window.innerWidth and window.innerHeight)
import { useState, useEffect } from 'react';
/**
* Custom React Hook useWindowSize
* @returns width: {Number}, height: {Number}
*/
export function useWindowSize() {
const isClient = typeof window === 'object';
function getSize() {
return {
width: isClient ? window.innerWidth : undefined,
height: isClient ? window.innerHeight : undefined,
};
}
const [windowSize, setWindowSize] = useState(getSize());
useEffect(() => {
if (!isClient) {
return false;
}
function handleResize() {
setWindowSize(getSize());
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []); /* eslint-disable-line */
return windowSize;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment