Svelte use:action for element resize notifications using ResizeObserver.
Small. Efficient. SSR Friendly.
You need to know when an Element changes size, as efficiently as possible, adding as few bytes to your project as possible.
The existing packages I looked at all had one or more issues:
This package is simple, fast and efficient. It is only 231 bytes minified, 195 bytes minified and gzipped. This is the built output, all it adds to your app:
var r=new WeakMap,s;function b(e,t){return s=s||new ResizeObserver(i=>{for(let l of i){let n=r.get(l.target);n&&n(l)}}),r.set(e,t),s.observe(e),{destroy(){s.unobserve(e),r.delete(e)}}}export{b as resize};
Import using your package manager of choice, e.g.:
pnpm i svelte-resize-observer-action
Import and apply to your HTML element. Provide the function that will be called with the ResizeObserverEntry object.
<script lang="ts">
  import { resize } from 'svelte-resize-observer-action'
  let width: number
  let height: number
  function onResize(entry: ResizeObserverEntry) {
    width = entry.contentRect.width
    height = entry.contentRect.height
  }
</script>
<div use:resize={onResize}>
  {width}w x {height}h
</div>
use:actionImport inside your use:action module:
import { resize } from 'svelte-resize-observer-action'
Apply to the element passed in to your use:action and call the destroy method when your action is destroyed:
type Render = (ctx: CanvasRenderingContext2D) => void
export function panzoom(canvas: HTMLCanvasElement, render: Render) {
  const ctx = canvas.getContext('2d')!
  // use resize action to watch element size
  const resizeManager = resize(canvas, entry => {
    // handle canvas size change and re-render
    render(ctx)
  })
  // rest of use:action implementation
  return {
    destroy() {
      // remember to call destroy when this action is destroyed
      resizeManager.destroy()
    },
  }
}