What is @react-hook/window-size?
@react-hook/window-size is a React hook that allows you to easily get the current window size and respond to window resize events. It provides a simple API to access the width and height of the window, making it useful for responsive design and dynamic layout adjustments.
What are @react-hook/window-size's main functionalities?
Get Window Size
This feature allows you to get the current width and height of the window. The `useWindowSize` hook returns an array with the width and height, which you can use to render responsive components.
import { useWindowSize } from '@react-hook/window-size';
function MyComponent() {
const [width, height] = useWindowSize();
return (
<div>
<p>Window width: {width}px</p>
<p>Window height: {height}px</p>
</div>
);
}
Custom Throttle
This feature allows you to throttle the resize event updates. By passing a number to `useWindowSize`, you can control how often the window size is updated, which can improve performance by reducing the frequency of re-renders.
import { useWindowSize } from '@react-hook/window-size';
function MyComponent() {
const [width, height] = useWindowSize(250); // Throttle updates every 250ms
return (
<div>
<p>Window width: {width}px</p>
<p>Window height: {height}px</p>
</div>
);
}
Other packages similar to @react-hook/window-size
react-use
react-use is a collection of essential React hooks, including a `useWindowSize` hook. It provides similar functionality to @react-hook/window-size but also includes a wide variety of other hooks for different use cases, making it a more comprehensive solution for managing state and side effects in React applications.
react-responsive
react-responsive is a package that allows you to create media query components in React. While it doesn't provide a direct hook for window size, it offers a more declarative approach to handling responsive design by allowing you to define breakpoints and render different components based on the current viewport size.
use-resize-observer
use-resize-observer is a React hook that uses the ResizeObserver API to track the size of a DOM element. While it is more focused on element size rather than window size, it can be used to achieve similar results by observing the document's root element. It provides more granular control over resizing behavior compared to @react-hook/window-size.
@react-hook/window-size
React hooks for monitoring changes to the size of the window.
Installation
yarn add @react-hook/window-size
Usage
import {useWindowSize, useWindowWidth, useWindowHeight} from '@react-hook/window-size'
const F = props => {
const [width, height] = useWindowSize(
360 ,
720 ,
{wait: 100}
)
}
import {useWindowSize, useWindowWidth, useWindowHeight} from '@react-hook/window-size/throttled'
const F = props => {
const [width, height] = useWindowSize(
360 ,
720 ,
{fps: 30}
)
}