Skip to content
Elements

useResizeObserver

Observes one or more elements for size changes using the ResizeObserver API. Targets can be Ref, MaybeElement, or a plain Element.

Resize Observer

Resize the textarea to see width & height update.

width
0px
height
0px
import {
import useRef$
useRef$
,
const useResizeObserver: (target: MaybeEventTarget | MaybeEventTarget[], callback: ResizeObserverCallback, options?: DeepMaybeObservable<UseResizeObserverOptions>) => UseResizeObserverReturn
useResizeObserver
} from "@usels/web";
import {
function useCallback<T extends Function>(callback: T, deps: DependencyList): T

useCallback will return a memoized version of the callback that only changes if one of the inputs has changed.

useCallback
} from "react";
function
function Component(): JSX.Element
Component
() {
const
const el$: any
el$
=
import useRef$
useRef$
<
interface HTMLDivElement
HTMLDivElement
>();
const
const handleResize: ResizeObserverCallback
handleResize
=
useCallback<ResizeObserverCallback>(callback: ResizeObserverCallback, deps: DependencyList): ResizeObserverCallback

useCallback will return a memoized version of the callback that only changes if one of the inputs has changed.

useCallback
<
type ResizeObserverCallback = /*unresolved*/ any
ResizeObserverCallback
>((
entries: any
entries
) => {
const {
const width: any
width
,
const height: any
height
} =
entries: any
entries
[0].
any
contentRect
;
any
console
.
any
log
(
const width: any
width
,
const height: any
height
);
}, []);
function useResizeObserver(target: MaybeEventTarget | MaybeEventTarget[], callback: ResizeObserverCallback, options?: DeepMaybeObservable<UseResizeObserverOptions>): UseResizeObserverReturn
useResizeObserver
(
const el$: any
el$
,
const handleResize: ResizeObserverCallback
handleResize
);
return <
JSX.IntrinsicElements.div: DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div
RefAttributes<HTMLDivElement>.ref?: Ref<HTMLDivElement> | undefined

Allows getting a ref to the component instance. Once the component unmounts, React will set ref.current to null (or call the ref with null if you passed a callback ref).

ref
={
const el$: any
el$
} />;
}
useResizeObserver(el$, handleResize, { box: "border-box" });
const { stop } = useResizeObserver(el$, handleResize);
stop();
const { isSupported$ } = useResizeObserver(el$, handleResize);
console.log(isSupported$.get()); // Observable<boolean>
ParameterTypeDescription
targetMaybeEventTarget | MaybeEventTarget[]-
callbackResizeObserverCallback-
optionsUseResizeObserverOptions (optional)-
OptionTypeDefaultDescription
box"content-box" | "border-box" | "device-pixel-content-box"--

UseResizeObserverReturn

NameTypeDescription
stop() => void-
isSupported$ReadonlyObservable<boolean>-

View on GitHub