useWindowSize
Here's an example of a custom hook that uses the useState
and useEffect
Hooks to track the current window size:
import { useState, useEffect } from 'react'
function useWindowSize() {
const [windowSize, setWindowSize] = useState({
width: window.innerWidth,
height: window.innerHeight,
})
useEffect(() => {
function handleResize() {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
})
}
window.addEventListener('resize', handleResize)
return () => window.removeEventListener('resize', handleResize)
}, [])
return windowSize
}
This custom hook returns an object with width
and height
properties that represent the current window size. We use the useState
Hook to initialize the window size state and the useEffect
Hook to add a resize
event listener to the window. When the window is resized, we update the window size state with the new values.
To use this custom hook, you would simply call it in your functional component:
function MyComponent() {
const windowSize = useWindowSize()
return (
<div>
<p>
Current window size: {windowSize.width} x {windowSize.height}
</p>
</div>
)
}
In this example, we call the useWindowSize
hook to get the current window size and use it to display the width and height of the window. By using the useWindowSize
Hook, we can easily track the current window size and adjust our components accordingly.