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
- Pass in the callback function to run when the observer elements are resized.
- Start tracking the element's size with the
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
useRefhook and assign it to the element you want to observe.
- Call the
useEffecthook 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
- Return the cleanup function from
ResizeObserver.disconnect()to stop tracking the element when the component is unmounted.
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:
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.
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
Here are the complete code examples you can copy and paste 👇