Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
use-resize-observer
Advanced tools
A React hook that allows you to use a ResizeObserver to measure an element's size.
The use-resize-observer package provides a React hook that allows you to monitor an element for size changes. It is useful for responsive design and element-specific adjustments based on width and height. It leverages the ResizeObserver API to offer a simple and efficient way to react to size changes in components.
Basic usage for monitoring size changes
This code demonstrates how to use the use-resize-observer hook to monitor the size of a component. By destructuring `ref`, `width`, and `height` from the hook, you can easily track the dimensions of the element that the `ref` is attached to.
import useResizeObserver from 'use-resize-observer';
const MyComponent = () => {
const { ref, width, height } = useResizeObserver();
return (
<div ref={ref}>
The width is {width} and the height is {height}.
</div>
);
};
Using with a callback
This example shows how to use the hook with a callback function. The `onResize` option allows you to provide a function that will be called whenever the observed element's size changes, receiving the new `width` and `height` as parameters.
import useResizeObserver from 'use-resize-observer';
const MyComponent = () => {
const { ref } = useResizeObserver({
onResize: ({ width, height }) => {
console.log(`New size: ${width}x${height}`);
}
});
return <div ref={ref}>Resize me and check the console!</div>;
};
react-resize-detector is another package that provides components and hooks to listen to resize events. Compared to use-resize-observer, it offers more customization options, such as the ability to choose between a hook or a higher-order component for detecting resize events. However, use-resize-observer might be simpler to use for straightforward use cases.
resize-observer-polyfill is not a React-specific package but a polyfill for the ResizeObserver API. It can be used in conjunction with React but requires manual setup and teardown of the observer. use-resize-observer abstracts this setup, offering a more integrated React hook approach.
A React hook that allows you to use a ResizeObserver to measure an element's size.
yarn add use-resize-observer --dev
# or
npm install use-resize-observer --save-dev
Note that the default builds are not polyfilled! For instructions and alternatives, see the Transpilation / Polyfilling section.
import React from "react";
import useResizeObserver from "use-resize-observer";
const App = () => {
const { ref, width = 1, height = 1 } = useResizeObserver<HTMLDivElement>();
return (
<div ref={ref}>
Size: {width}x{height}
</div>
);
};
Note that "ref" here is a RefCallback
, not a RefObject
, meaning you won't be
able to access "ref.current" if you need the element itself.
To get the raw element, either you use your own RefObject (see later in this doc)
or you hook in the returned ref callback, like so:
RefCallback
import React, { useCallback, useEffect, useRef } from "react";
import useResizeObserver from "use-resize-observer";
const useMergedCallbackRef = (...callbacks: Function[]) => {
// Storing callbacks in a ref, so that we don't need to memoise them in
// renders when using this hook.
const callbacksRegistry = useRef<Function[]>(callbacks);
useEffect(() => {
callbacksRegistry.current = callbacks;
}, [...callbacks]);
return useCallback((element) => {
callbacksRegistry.current.forEach((callback) => callback(element));
}, []);
};
const App = () => {
const { ref, width = 1, height = 1 } = useResizeObserver<HTMLDivElement>();
const mergedCallbackRef = useMergedCallbackRef(
ref,
(element: HTMLDivElement) => {
// Do whatever you want with the `element`.
}
);
return (
<div ref={mergedCallbackRef}>
Size: {width}x{height}
</div>
);
};
ref
You can pass in your own ref instead of using the one provided. This can be useful if you already have a ref you want to measure.
const ref = useRef<HTMLDivElement>(null);
const { width, height } = useResizeObserver<HTMLDivElement>({ ref });
You can even reuse the same hook instance to measure different elements:
There might be situations where you have an element already that you need to measure.
ref
now accepts elements as well, not just refs, which means that you can do this:
const { width, height } = useResizeObserver<HTMLDivElement>({
ref: divElement,
});
The hook reacts to ref changes, as it resolves it to an element to observe.
This means that you can freely change the custom ref
option from one ref to
another and back, and the hook will start observing whatever is set in its options.
In certain cases you might want to delay creating a ResizeObserver instance.
You might provide a library, that only optionally provides observation features based on props, which means that while you have the hook within your component, you might not want to actually initialise it.
Another example is that you might want to entirely opt out of initialising, when
you run some tests, where the environment does not provide the ResizeObserver
.
You can do one of the following depending on your needs:
ref
RefCallback, or provide a custom ref conditionally,
only when needed. The hook will not create a ResizeObserver instance up until
there's something there to actually observe.By the default the hook will trigger a re-render on all changes to the target element's width and / or height.
You can opt out of this behaviour, by providing an onResize
callback function,
which'll simply receive the width and height of the element when it changes, so
that you can decide what to do with it:
import React from "react";
import useResizeObserver from "use-resize-observer";
const App = () => {
// width / height will not be returned here when the onResize callback is present
const { ref } = useResizeObserver<HTMLDivElement>({
onResize: ({ width, height }) => {
// do something here.
},
});
return <div ref={ref} />;
};
This callback also makes it possible to implement your own hooks that report only what you need, for example:
requestAnimationFrame
You might want to receive values less frequently than changes actually occur.
While this hook does not come with its own implementation of throttling / debouncing,
you can use the onResize
callback to implement your own version:
On initial mount the ResizeObserver will take a little time to report on the actual size.
Until the hook receives the first measurement, it returns undefined
for width
and height by default.
You can override this behaviour, which could be useful for SSR as well.
const { ref, width = 100, height = 50 } = useResizeObserver<HTMLDivElement>();
Here "width" and "height" will be 100 and 50 respectively, until the ResizeObserver kicks in and reports the actual size.
If you only want real measurements (only values from the ResizeObserver without any default values), then you can just leave defaults off:
const { ref, width, height } = useResizeObserver<HTMLDivElement>();
Here "width" and "height" will be undefined until the ResizeObserver takes its first measurement.
It's possible to apply styles conditionally based on the width / height of an element using a CSS-in-JS solution, which is the basic idea behind container/element queries:
By default the library provides transpiled ES5 modules in CJS / ESM module formats.
Polyfilling is recommended to be done in the host app, and not within imported libraries, as that way consumers have control over the exact polyfills being used.
That said, there's a polyfilled CJS module that can be used for convenience (Not affecting globals):
import useResizeObserver from "use-resize-observer/polyfilled";
MIT
7.0.0 (2020-11-11)
null
or undefined as the
ref, or if neither the default ref or RefCallback returned from the hook are
in use, then no ResizeObserver instance will get created until there's an
actual element to observe. Resolves: #42ref
option now accepts raw elements as well.callbackRef
return value anymore.useResolvedElement
hook), to handle more edge cases with the way refs are handled.FAQs
A React hook that allows you to use a ResizeObserver to measure an element's size.
The npm package use-resize-observer receives a total of 860,137 weekly downloads. As such, use-resize-observer popularity was classified as popular.
We found that use-resize-observer demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.