Skip to content

Instantly share code, notes, and snippets.

@GGrassiant
Created September 19, 2020 19:45
Show Gist options
  • Save GGrassiant/4075328708cba0d589534f73cc636be8 to your computer and use it in GitHub Desktop.
Save GGrassiant/4075328708cba0d589534f73cc636be8 to your computer and use it in GitHub Desktop.
useResize

useResize custom hook.

Custom hook as per Sophie Alpert on StackOverflow function that returns the height and width on each update of the window

import React, { useLayoutEffect, useState } from 'react';
const useWindowSize = () => {
const [size, setSize] = useState([0, 0]);
useLayoutEffect(() => {
const updateSize = () => {
setSize([window.innerWidth, window.innerHeight]);
};
window.addEventListener('resize', updateSize);
updateSize();
return () => window.removeEventListener('resize', updateSize);
}, []);
return size;
};
// hooks to be used in the component to get access to size
const ShowWindowDimensions= () => {
const [width, height] = useWindowSize();
return [width, height];
};
export default ShowWindowDimensions;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment