useFloating
A lightweight hook built on @floating-ui for positioning floating elements like tooltips, dropdowns, or popovers.
✅ Features
- Auto-positioning
 - Collision detection
 - Flexible placements
 
📦 Usage
1import { useFloating } from './useFloating' 2 3const { refs, floatingStyles } = useFloating({ placement: 'bottom' }) 4 5return ( 6 <> 7 <button ref={refs.setReference}>Open</button> 8 <div ref={refs.setFloating} style={floatingStyles}> 9 I'm floating! 10 </div> 11 </> 12)
📋 Source Code
This is the full implementation of useFloating
1import { useEffect, useRef, useState } from 'react'
2
3export function useFloating() {
4  const ref = useRef<HTMLElement>(null)
5  const [position, setPosition] = useState({ top: 0, left: 0 })
6
7  const updatePosition = () => {
8    const el = ref.current
9    if (!el) return
10    const rect = el.getBoundingClientRect()
11    setPosition({
12      top: rect.bottom + window.scrollY,
13      left: rect.left + window.scrollX,
14    })
15  }
16
17  useEffect(() => {
18    updatePosition()
19    window.addEventListener('scroll', updatePosition, true)
20    return () => window.removeEventListener('scroll', updatePosition, true)
21  }, [])
22
23  return { ref, position }
24}
25