HomeTypeScript-friendly useSize from @react-hook/resize-observer.

TypeScript-friendly useSize from @react-hook/resize-observer.

Published: 3/19/2024

So you went to https://www.npmjs.com/package/@react-hook/resize-observer and copied useSize, but it has a bunch of typescript errors, and it pisses you off (I know it does).

Here's a version that is TypeScript-friendly... And not just that, it's a complete file you can put in your project and import from your components:

import useResizeObserver from "@react-hook/resize-observer"
import { useLayoutEffect, useState } from "react"

const useSize = (target:any) => {
  const [size, setSize] = useState<DOMRectReadOnly>()

  useLayoutEffect(() => {
    setSize(target.current.getBoundingClientRect())
  }, [target])

  // Where the magic happens
  useResizeObserver(target, (entry) => setSize(entry.contentRect));
  return size
}

export default useSize;

About Code with Node.js

This is a personal blog and reference point of a Node.js developer.

I write and explain how different Node and JavaScript aspects work, as well as research popular and cool packages, and of course fail time to time.