useResize custom hook.
Custom hook as per Sophie Alpert on StackOverflow function that returns the height and width on each update of the window
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; |