Using the Resize Observer in Javascript
Unlike window
, DOM elements don't have a resize
event that you can attach an event listener on. To listen to resize events on a DOM element you need to use the ResizeObserver API:
- Create the resize observer with
new ResizeObserver(...)
. - Pass in the callback function to run when the observer elements are resized.
- Start tracking the element's size with the
.observe(element)
function.
Using the Resize Observer in React
The most common way to use resize observer in react is by using useEffect
to start tracking an element's size when the component is mounted. Here's how to do it:
- Create a ref object using the
useRef
hook and assign it to the element you want to observe. - Call the
useEffect
hook in your React component with a callback function[]
as the dependency array. - Inside, create the resize observer using
new ResizeObserver(...)
pass it the handler function. - Start tracking the element's size with a call to
ResizeObserver.observe(element)
. - Return the cleanup function from
useEffect
that callsResizeObserver.disconnect()
to stop tracking the element when the component is unmounted.
The useResizeObserver
hook
If you need to use resize observers often, writing the above code can become cumbersome and repetitive. You can move it to a reusable hook that allows you to easily keep track of the element's dimensions:
You can then use it like this:
The onResize
function must preserve its references between component re-renders, that's why we wrap it with the useCallback
hook. Otherwise, the resize observer would be re-created on every re-render, which may lead to performance issues.
Conclusion
Using the resize observer in React is the same as using it in JavaScript, and you can use the useEffect
hook to hook into the React component lifecycle, for instance, to start observing when the component is mounted.
There may be a case when you want to start observing when some event happens, e.g. a button is pressed. The important point is that the resize observer must keep the same reference between component re-renders.
To do that, you can assign the ResizeObserver
instance to a ref object created with a call to useRef
and access it on the .current
property.
Here are the complete code examples you can copy and paste 👇