Skip to content

Instantly share code, notes, and snippets.

@stekhn
Created June 10, 2022 08:49
Show Gist options
  • Save stekhn/b2f2b5ba4f6fe4f0766f6d3ae2df5a01 to your computer and use it in GitHub Desktop.
Save stekhn/b2f2b5ba4f6fe4f0766f6d3ae2df5a01 to your computer and use it in GitHub Desktop.
React hook for responsive width and height with support for resize events
import { useState, useEffect } from 'react';
const getDimensions = () => {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height
};
};
export const useDimensions = () => {
const [dimensions, setDimensions] = useState(getDimensions());
useEffect(() => {
const handleResize = () => {
setDimensions(getDimensions());
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return dimensions;
};
// Usage
// const { width } = useDimensions();
// useEffect(() => {
// setWidth(width)
// }, [width]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment