⚡️ Live Demo

react-using-resize-observer

Go try it out on CodeSandbox

👨‍💻 Code

GitHub - furkanhr/react-using-resize-observer: Created with CodeSandbox

Go fork the live example

📖 Docs

ResizeObserver - Web APIs | MDN

Go learn more in detail on MDN

1. Start by defining refs

Let’s start by defining an empty ref type of ResizeObserver. This way it lets us to create a single instance once then also remove it after unmount.

const resizeObserver = useRef<ResizeObserver>()

We also need a reference to our target — or observed — element. Don’t forget to pass it to the target component.

const targetRef = useRef(null)

// ...

return (
	// ...
	<div className="target-element" ref={targetRef} />
)

The important point about the refs is that they are always initially null and then they get initialized after mount. So we need a way to know if the component mounted, this will do:

const [isMounted, setMounted] = useState(false)

useEffect(() => {
	setMounted(true)
}, [])

2. Plan the start and the end

Everything starts at mount then everything ends after unmount just like we usually do with event listeners.

useEffect(() => {
  addResizeObserver();

  return () => removeResizeObserver();
}, [isMounted]);