Skip to content

Instantly share code, notes, and snippets.

@natac13
Created February 24, 2021 13:44
Show Gist options
  • Save natac13/20f32f548c8350556cc10d511d8439ce to your computer and use it in GitHub Desktop.
Save natac13/20f32f548c8350556cc10d511d8439ce to your computer and use it in GitHub Desktop.
useHeight.tsx
import { useState, useRef, useLayoutEffect, RefObject } from 'react'
// https://css-tricks.com/making-sense-of-react-spring/
export function useHeight({ on = true } = {}): [
RefObject<HTMLDivElement>,
number | string
] {
const ref = useRef<HTMLDivElement>(null)
const [height, set] = useState<number | string>(0)
const heightRef = useRef(height)
const [ro] = useState(
() =>
// @ts-expect-error
new ResizeObserver(() => {
if (ref.current && heightRef.current !== ref.current.offsetHeight) {
heightRef.current = ref.current.offsetHeight
set(ref.current.offsetHeight)
}
})
)
useLayoutEffect(() => {
if (on && ref.current) {
set(ref?.current.offsetHeight)
ro.observe(ref?.current, {})
}
return () => ro.disconnect()
}, [on, ro])
return [ref, height]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment