4 min readLoading views
Floating UI - useFloating
A deep dive into Floating UI's useFloating hook - understanding how it bridges the gap between an imperative async positioning API and React's declarative model through clever patterns like dual state/ref management, flushSync for smooth updates, and lifecycle subscriptions.
Introduction
This is the third article in my Floating UI deep dive series. If you haven't already, I recommend reading the previous articles first:
-
Floating UI - Coordinate System
- Understanding browser coordinates, placements, axes, and
computeCoordsFromPlacement
- Understanding browser coordinates, placements, axes, and
-
Floating UI - Middleware Deep Dive
- The middleware pipeline:
offset,shift,flip, anddetectOverflow
- The middleware pipeline:
In those articles, we explored how Floating UI calculates positions and adjusts them through middleware. Now we'll see how the React adapter, useFloating, brings it all together.
At the core of Floating UI lies computePosition - an imperative, async function that orchestrates everything we learned: it calculates initial coordinates using computeCoordsFromPlacement, then runs them through the middleware pipeline (offset → shift → flip → etc.) to produce final positioning data.
The useFloating hook is the React adapter that makes this imperative API work seamlessly with React's declarative paradigm. Understanding how it works reveals elegant solutions to common React challenges.
The Core Challenge
Here's the fundamental tension useFloating must resolve:
// computePosition is IMPERATIVE and ASYNCcomputePosition(referenceEl, floatingEl, config).then((data) => { // Returns { x, y, placement, middlewareData, ... }});// But React is DECLARATIVE and SYNCHRONOUSconst [data, setData] = useState({ x: 0, y: 0 });return <div style={{ transform: `translate(${data.x}px, ${data.y}px)` }} />;The hook needs to bridge these two worlds while handling:
- Element references - Both the trigger (reference) and floating element need to be tracked
- Async updates - Position calculations happen asynchronously
- Performance - Updates must be smooth during scroll/resize
- Lifecycle - Proper cleanup when elements unmount
Pattern 1: Dual State + Ref
The Problem with State or Ref Alone
React has two ways to store values, each with trade-offs:
useState | useRef | |
|---|---|---|
| Behavior | Triggers re-render on change | Does NOT trigger re-render |
| Access | Value captured in closures (stale state risk) | Always current via . |
| Best For | Data that drives UI | Mutable values, DOM references |
Using only refs means no re-renders:
// Problem: Ref changes don't trigger re-rendersconst referenceRef = useRef(null);useLayoutEffect(() => { if (referenceRef.current && floatingRef.current) { update(); // When does this re-run? Never automatically! }}, []); // Can't depend on ref.current - React won't track itUsing only state risks stale closures:
// Problem: State captured in closures becomes staleconst [reference, setReference] = useState(null);const update = useCallback(() => { // `reference` is captured when useCallback was created // If reference changes, this callback still has the OLD value! computePosition(reference, floating, config);}, [reference]); // Must add dependency, recreating callback every timeThe Solution: Use Both
useFloating stores elements in both state and refs:
const [_reference, _setReference] = React.useState<RT | null>(null);const referenceRef = React.useRef<RT | null>(null);const setReference = React.useCallback((node: RT | null) => { if (node !== referenceRef.current) { referenceRef.current = node; // Immediate access for computePosition _setReference(node); // Triggers re-render to run effects }}, []);This gives us:
- State triggers
useLayoutEffectwhen elements change - Ref provides always-current value for async callbacks
Pattern 2: useLatestRef for Fresh Values
Another stale closure problem: the update callback needs current values for platform, open, and whileElementsMounted, but adding them as dependencies would recreate the callback constantly.
function useLatestRef<T>(value: T) { const ref = useRef(value); useLayoutEffect(() => { ref.current = value; }); return ref;}This pattern keeps a ref synchronized with the latest prop value:
const platformRef = useLatestRef(platform);const openRef = useLatestRef(open);const update = useCallback(() => { // Always gets the CURRENT value, even though it's not in deps if (platformRef.current) { config.platform = platformRef.current; } isPositioned: openRef.current !== false,}, []); // Stable callback - no dependencies needed for these values!The Update Flow
Timeline of a Typical Interaction
Flowchart
The update Function
const update = React.useCallback(() => { // Guard: Both elements must exist if (!referenceRef.current || !floatingRef.current) { return; } const config: ComputePositionConfig = { placement, strategy, middleware: latestMiddleware, }; if (platformRef.current) { config.platform = platformRef.current; } computePosition(referenceRef.current, floatingRef.current, config).then( (data) => { const fullData = { ...data, isPositioned: openRef.current !== false, }; // Guard: Component might have unmounted during async operation // Guard: Skip if data hasn't actually changed (prevents loops) if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) { dataRef.current = fullData; ReactDOM.flushSync(() => { setData(fullData); }); } }, );}, [latestMiddleware, placement, strategy, platformRef, openRef]);Why flushSync?
React normally batches state updates for performance. But for positioning, we need immediate updates to prevent visual lag.
flushSync vs Batched Updates
Click "Start Animation" to see a reference element move automatically. Watch how the tooltip follows - the batched version lags behind and jumps, while flushSync keeps up smoothly.
import React, { useState, useRef, useEffect, useCallback } from 'react';import { flushSync } from 'react-dom';export default function App() { const [isRunning, setIsRunning] = useState(false); const [referenceX, setReferenceX] = useState(50); // Without flushSync - uses requestAnimationFrame batching simulation const [batchedX, setBatchedX] = useState(50); const [batchedRenders, setBatchedRenders] = useState(0); const batchedPending = useRef([]); const batchedFrameId = useRef(null); // With flushSync - immediate updates const [syncX, setSyncX] = useState(50); const [syncRenders, setSyncRenders] = useState(0); const animationRef = useRef(null); const startTimeRef = useRef(null); // Simulates how computePosition works: // 1. Async calculation (setTimeout simulates the Promise) // 2. Then setState to update position const simulateComputePosition = useCallback((targetX, useFlushSync) => { // Simulate async computePosition (5-15ms like real positioning) const delay = Math.random() * 10 + 5; setTimeout(() => { if (useFlushSync) { // flushSync: Paint IMMEDIATELY, don't wait flushSync(() => { setSyncX(targetX); setSyncRenders((r) => r + 1); }); } else { // Normal setState: Gets batched with other pending updates // We simulate React's batching by collecting updates and applying at rAF batchedPending.current.push(targetX); if (!batchedFrameId.current) { batchedFrameId.current = requestAnimationFrame(() => { // React would batch all pending setState calls // Only the LAST value actually renders (others are "lost") const lastValue = batchedPending.current[batchedPending.current.length - 1]; setBatchedX(lastValue); setBatchedRenders((r) => r + 1); batchedPending.current = []; batchedFrameId.current = null; }); } } }, delay); }, []); // Animation loop - moves reference element in a sine wave useEffect(() => { if (!isRunning) { if (animationRef.current) { cancelAnimationFrame(animationRef.current); } return; } startTimeRef.current = performance.now(); const animate = (timestamp) => { const elapsed = timestamp - startTimeRef.current; // Sine wave movement: oscillates between 15% and 85% const newX = 50 + Math.sin(elapsed / 300) * 35; setReferenceX(newX); // Simulate scroll event firing - both get the same target simulateComputePosition(newX, false); // batched simulateComputePosition(newX, true); // flushSync animationRef.current = requestAnimationFrame(animate); }; animationRef.current = requestAnimationFrame(animate); return () => { if (animationRef.current) { cancelAnimationFrame(animationRef.current); } }; }, [isRunning, simulateComputePosition]); const handleToggle = () => { if (isRunning) { setIsRunning(false); } else { // Reset setReferenceX(50); setBatchedX(50); setSyncX(50); setBatchedRenders(0); setSyncRenders(0); batchedPending.current = []; setIsRunning(true); } }; const reset = () => { setIsRunning(false); setReferenceX(50); setBatchedX(50); setSyncX(50); setBatchedRenders(0); setSyncRenders(0); batchedPending.current = []; }; return ( <div style={styles.container}> <div style={styles.grid}> {/* Without flushSync */} <div style={styles.card}> <div style={{ ...styles.cardHeader, background: '#fef2f2', color: '#ef4444' }}>Without flushSync</div> <div style={styles.viewport}> {/* Reference (gray, shows target) */} <div style={{ ...styles.reference, left: `${referenceX}%`, opacity: 0.3, }} > Target </div> {/* Actual reference position */} <div style={{ ...styles.reference, left: `${referenceX}%`, top: '30px', }} > Reference </div> {/* Tooltip - follows with lag */} <div style={{ ...styles.tooltip, left: `${batchedX}%`, borderColor: '#ef4444', background: 'rgba(239, 68, 68, 0.1)', }} > Tooltip </div> {/* Lag indicator line */} {isRunning && Math.abs(referenceX - batchedX) > 2 && ( <svg style={styles.lagLine}> <line x1={`${referenceX}%`} y1="76" x2={`${batchedX}%`} y2="100" stroke="#ef4444" strokeWidth="2" strokeDasharray="4" /> </svg> )} </div> <div style={styles.stats}> <div style={styles.statRow}> <span>Lag:</span> <span style={{ fontWeight: '700', color: '#ef4444' }}> {Math.abs(referenceX - batchedX).toFixed(1)}px </span> </div> <div style={styles.statRow}> <span>Renders:</span> <span style={{ fontWeight: '600' }}>{batchedRenders}</span> </div> </div> <div style={styles.explanation}> Updates batch together, only last position renders. Tooltip jumps and lags behind. </div> </div> {/* With flushSync */} <div style={styles.card}> <div style={{ ...styles.cardHeader, background: '#f0fdf4', color: '#10b981' }}>With flushSync</div> <div style={styles.viewport}> {/* Reference (gray, shows target) */} <div style={{ ...styles.reference, left: `${referenceX}%`, opacity: 0.3, }} > Target </div> {/* Actual reference position */} <div style={{ ...styles.reference, left: `${referenceX}%`, top: '30px', }} > Reference </div> {/* Tooltip - follows immediately */} <div style={{ ...styles.tooltip, left: `${syncX}%`, borderColor: '#10b981', background: 'rgba(16, 185, 129, 0.1)', }} > Tooltip </div> </div> <div style={styles.stats}> <div style={styles.statRow}> <span>Lag:</span> <span style={{ fontWeight: '700', color: '#10b981' }}>{Math.abs(referenceX - syncX).toFixed(1)}px</span> </div> <div style={styles.statRow}> <span>Renders:</span> <span style={{ fontWeight: '600' }}>{syncRenders}</span> </div> </div> <div style={styles.explanation}>Each update paints immediately. Tooltip tracks reference smoothly.</div> </div> </div> <div style={styles.controlPanel}> <button onClick={handleToggle} style={{ ...styles.button, background: isRunning ? '#ef4444' : '#10b981', }} > {isRunning ? 'Stop Animation' : 'Start Animation'} </button> <button onClick={reset} style={{ ...styles.button, background: '#6b7280' }}> Reset </button> </div> </div> );}const styles = { container: { fontFamily: "'Figtree', -apple-system, sans-serif", padding: '20px', background: '#f9fafb', minHeight: '100vh', margin: 'auto 0', }, controlPanel: { display: 'flex', justifyContent: 'center', gap: '12px', marginBottom: '20px', }, button: { padding: '10px 24px', fontSize: '14px', fontWeight: '600', color: 'white', border: 'none', borderRadius: '8px', cursor: 'pointer', transition: 'transform 0.1s', }, grid: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '20px', }, card: { background: '#ffffff', borderRadius: '12px', padding: '16px', boxShadow: '0 1px 3px rgba(0,0,0,0.1)', }, cardHeader: { fontSize: '14px', fontWeight: '700', marginBottom: '12px', padding: '8px 12px', borderRadius: '6px', textAlign: 'center', }, viewport: { position: 'relative', height: '140px', background: '#f8fafc', borderRadius: '8px', border: '2px dashed #e5e7eb', overflow: 'hidden', }, reference: { position: 'absolute', top: '30px', transform: 'translateX(-50%)', padding: '6px 12px', background: 'rgba(99, 102, 241, 0.1)', border: '2px solid #001858', borderRadius: '6px', fontSize: '11px', fontWeight: '600', color: '#001858', whiteSpace: 'nowrap', transition: 'none', }, tooltip: { position: 'absolute', top: '85px', transform: 'translateX(-50%)', padding: '6px 12px', border: '2px solid #33272a', borderRadius: '6px', fontSize: '11px', fontWeight: '600', color: '#33272a', whiteSpace: 'nowrap', transition: 'none', }, lagLine: { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', pointerEvents: 'none', }, stats: { marginTop: '12px', padding: '10px', background: '#f8fafc', borderRadius: '6px', fontSize: '12px', color: '#6b7280', }, statRow: { display: 'flex', justifyContent: 'space-between', marginBottom: '4px', }, explanation: { marginTop: '8px', fontSize: '11px', color: '#9ca3af', textAlign: 'center', lineHeight: '1.4', },};Key insight: flushSync renders MORE often (see render count), but each render shows the CURRENT position. Batching renders less often, but skips intermediate positions causing visual lag.
Safety Guards in update()
The update function has three layers of protection:
// Guard 1: Elements must existif (!referenceRef.current || !floatingRef.current) { return;}// Guard 2: Component must still be mounted (checked after async)if (isMountedRef.current && ...) { // Safe to update}// Guard 3: Data must have changed (prevents infinite loops)if (!deepEqual(dataRef.current, fullData)) { // Worth updating}The mounted check is crucial for async operations:
Flowchart
The isPositioned Flag
isPositioned answers: "Has the floating element been placed at least once?"
This is critical for animations:
// Common pattern: Fade in AFTER positioned<div style={{ ...floatingStyles, opacity: isPositioned ? 1 : 0, transition: isPositioned ? 'opacity 0.2s' : 'none', }}> Tooltip content</div>Without isPositioned:
Flowchart
With isPositioned:
Flowchart
Connection to the open Prop
// When computing positionisPositioned: openRef.current !== false, // When open changes to false useLayoutEffect(() => { if (open === false && dataRef.current.isPositioned) { dataRef.current.isPositioned = false; setData((data) => ({ ...data, isPositioned: false })); } }, [open]);This resets isPositioned when the floating element closes, so it can animate in again on the next open.
whileElementsMounted: The Subscription Lifecycle
The Problem
computePosition gives you position at ONE moment. But elements move when:
- User scrolls
- Window resizes
- Content changes size
- Layout shifts occur
The Solution
whileElementsMounted is a callback that sets up continuous updates:
import { autoUpdate } from '@floating-ui/dom';const { refs } = useFloating({ whileElementsMounted: autoUpdate, // or with options: whileElementsMounted: (reference, floating, update) => { return autoUpdate(reference, floating, update, { ancestorScroll: true, ancestorResize: true, elementResize: true, layoutShift: true, animationFrame: false, }); },});Lifecycle Visualization
Flowchart
Why Use a Ref for whileElementsMounted?
const whileElementsMountedRef = useLatestRef(whileElementsMounted);If we used the prop directly in the effect dependencies:
// Problem: Effect re-runs on every render if user passes inline functionuseLayoutEffect(() => { if (referenceEl && floatingEl && whileElementsMounted) { return whileElementsMounted(referenceEl, floatingEl, update); }}, [referenceEl, floatingEl, whileElementsMounted]); // Unstable!// User's code:useFloating({ whileElementsMounted: (ref, float, update) => autoUpdate(ref, float, update), // ↑ New function every render = effect re-runs constantly!});With the ref pattern:
const whileElementsMountedRef = useLatestRef(whileElementsMounted);useLayoutEffect(() => { if (referenceEl && floatingEl && whileElementsMountedRef.current) { return whileElementsMountedRef.current(referenceEl, floatingEl, update); }}, [referenceEl, floatingEl]); // Stable deps! Ref not in dependency array.floatingStyles: The CSS Output
const floatingStyles = useMemo(() => { const initialStyles = { position: strategy, left: 0, top: 0, }; if (!elements.floating) { return initialStyles; } const x = roundByDPR(elements.floating, data.x); const y = roundByDPR(elements.floating, data.y); if (transform) { return { ...initialStyles, transform: `translate(${x}px, ${y}px)`, ...(getDPR(elements.floating) >= 1.5 && { willChange: 'transform' }), }; } return { position: strategy, left: x, top: y, };}, [strategy, transform, elements.floating, data.x, data.y]);Transform vs Layout Positioning
| Aspect | transform | Layout (left/top) |
|---|---|---|
| Performance | GPU accelerated | Triggers layout recalc |
| Subpixel render | Smooth | Can be blurry |
| Animation | Smooth | Can be janky |
| Stacking context | Creates new one | Doesn't |
Transform (default):
.floating { position: absolute; left: 0; top: 0; transform: translate(150px, 200px); will-change: transform; /* Only on high DPR screens */}Layout positioning (transform: false):
.floating { position: absolute; left: 150px; top: 200px;}import React, { useState, useEffect } from 'react';const colors = { bgPage: '#f0f2f5', sidebar: '#ffffff', border: '#d1d5db', layoutFill: '#fee2e2', // Light Red layoutStroke: '#ef4444', // Red transformFill: '#dcfce7', // Light Green transformStroke: '#22c55e', // Green pushedFill: '#f3f4f6', // Light Gray pushedStroke: '#6b7280', // Gray textMuted: '#4b5563',};const styles = { app: { display: 'flex', backgroundColor: colors.bgPage, color: '#1f2937', }, sidebar: { width: '320px', backgroundColor: colors.sidebar, borderRight: `1px solid ${colors.border}`, padding: '24px', display: 'flex', flexDirection: 'column', boxShadow: '4px 0 24px rgba(0,0,0,0.02)', zIndex: 10, overflowY: 'auto', }, sidebarHeader: { fontSize: '1.25em', fontWeight: '700', borderBottom: `1px solid ${colors.border}`, paddingBottom: '16px', marginBottom: '24px', color: '#111827', }, canvas: { flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '40px', backgroundColor: '#fafafa', }, containerWrapper: { width: '100%', maxWidth: '600px', background: 'white', padding: '40px', borderRadius: '12px', boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)', border: `1px solid ${colors.border}`, }, container: { width: '100%', height: '120px', border: `2px dashed ${colors.border}`, display: 'flex', alignItems: 'center', padding: '0 20px', position: 'relative', borderRadius: '8px', backgroundColor: '#fdfdfd', overflow: 'hidden', }, box: { width: '80px', height: '80px', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 'bold', borderRadius: '8px', fontSize: '14px', flexShrink: 0, boxShadow: '0 4px 6px rgba(0,0,0,0.05)', transition: 'background-color 0.2s, border-color 0.2s', }, layoutBox: { backgroundColor: colors.layoutFill, border: `2px solid ${colors.layoutStroke}`, color: colors.layoutStroke, }, transformBox: { position: 'absolute', top: '18px', left: '20px', backgroundColor: colors.transformFill, border: `2px solid ${colors.transformStroke}`, color: colors.transformStroke, zIndex: 10, }, pushedBox: { width: '80px', height: '80px', backgroundColor: colors.pushedFill, border: `2px solid ${colors.pushedStroke}`, color: colors.pushedStroke, display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 'bold', borderRadius: '8px', fontSize: '14px', flexShrink: 0, marginLeft: '10px', }, explanation: { fontSize: '13px', color: colors.textMuted, marginTop: 'auto', lineHeight: '1.5', backgroundColor: '#f3f4f6', padding: '16px', borderRadius: '8px', border: `1px solid ${colors.border}`, }, controlGroup: { marginBottom: '24px', }, label: { display: 'block', marginBottom: '8px', fontWeight: '600', fontSize: '14px', color: '#374151', }, select: { width: '100%', padding: '10px', borderRadius: '6px', border: `1px solid ${colors.border}`, backgroundColor: 'white', fontSize: '14px', cursor: 'pointer', }, range: { width: '100%', cursor: 'pointer', accentColor: '#4f46e5', }, checkboxWrapper: { display: 'flex', alignItems: 'center', gap: '8px', marginTop: '8px', fontSize: '14px', cursor: 'pointer', }, infoTag: { display: 'inline-block', padding: '2px 6px', borderRadius: '4px', fontSize: '11px', fontWeight: 'bold', marginLeft: '8px', backgroundColor: '#e0e7ff', color: '#4338ca', },};const App = () => { const [x, setX] = useState(10.5); // Start with fractional value to demonstrate const [mode, setMode] = useState('layout'); const [snapToDPR, setSnapToDPR] = useState(false); const [dpr, setDpr] = useState(1); useEffect(() => { if (typeof window !== 'undefined') { setDpr(window.devicePixelRatio || 1); } }, []); // DPR Handling Logic const roundByDPR = (value) => { return Math.round(value * dpr) / dpr; }; const effectiveX = snapToDPR ? roundByDPR(x) : x; return ( <div style={styles.app}> <div style={styles.sidebar}> <h3 style={styles.sidebarHeader}> <span style={styles.infoTag}>DPR: {dpr}</span> </h3> <div style={styles.controlGroup}> <label style={styles.label}>Animation Mode</label> <select value={mode} onChange={(e) => { setMode(e.target.value); setX(10.5); }} style={styles.select} > <option value="layout">Layout (left/margin)</option> <option value="transform">Composite (transform)</option> </select> </div> <div style={styles.controlGroup}> <label style={styles.label}> Position X: <span style={{ fontFamily: 'monospace' }}>{effectiveX}px</span> </label> <input type="range" min="10" max="350" step="0.1" value={x} onChange={(e) => setX(parseFloat(e.target.value))} style={styles.range} /> <label style={styles.checkboxWrapper}> <input type="checkbox" checked={snapToDPR} onChange={(e) => setSnapToDPR(e.target.checked)} /> Snap to Physical Pixels (DPR) </label> </div> <div style={styles.explanation}> {mode === 'layout' ? ( <div> <p style={{ marginBottom: '8px', color: colors.layoutStroke, fontWeight: 'bold', display: 'flex', alignItems: 'center', gap: '6px', }} > ⚠️ Layout Positioning </p> <ul style={{ paddingLeft: '16px', margin: 0 }}> <li> <strong>Performance:</strong> Triggers expensive layout recalculations (CPU). </li> <li> <strong>Pixel Grid:</strong> Layout engines often force integer snapping automatically. </li> </ul> </div> ) : ( <div> <p style={{ marginBottom: '8px', color: colors.transformStroke, fontWeight: 'bold', display: 'flex', alignItems: 'center', gap: '6px', }} > ⚡ Transform (Composite) </p> <ul style={{ paddingLeft: '16px', margin: 0 }}> <li> <strong>Sub-pixels:</strong> Allows placing elements <i>between</i> pixels. </li> <li> <strong>Blur Risk:</strong> Without snapping, static elements at .5 coords may blur. </li> <li> <strong>Optimization:</strong>{' '} {dpr >= 1.5 ? 'High DPR detected; `will-change` applied.' : 'Standard DPR.'} </li> </ul> </div> )} {snapToDPR && ( <div style={{ marginTop: '12px', padding: '8px', background: '#e0e7ff', borderRadius: '4px', fontSize: '12px', color: '#3730a3', }} > <strong>Active:</strong> Coordinates are rounding to the nearest 1/{dpr} pixel to ensure sharp edges. </div> )} </div> </div> <div style={styles.canvas}> <h2 style={{ fontSize: '24px', fontWeight: 'bold', marginBottom: '20px' }}> {mode === 'layout' ? 'Layout Shift' : 'Hardware Accelerated'} </h2> <div style={styles.containerWrapper}> {mode === 'layout' ? ( <div style={styles.container}> <div style={{ ...styles.box, ...styles.layoutBox, marginLeft: `${effectiveX}px` }}>Layout</div> <div style={styles.pushedBox}>Sibling</div> </div> ) : ( <div style={styles.container}> <div style={{ ...styles.box, ...styles.transformBox, transform: `translateX(${effectiveX}px)`, willChange: dpr >= 1.5 ? 'transform' : 'auto', }} > Transform </div> <div style={{ ...styles.pushedBox, marginLeft: '10px', opacity: 0.5 }}>Sibling</div> </div> )} </div> <p style={{ marginTop: '20px', color: colors.textMuted, fontSize: '14px', textAlign: 'center' }}> Current Input: {x}px <br /> Rendered at: {effectiveX}px </p> </div> </div> );};export default App;DPR (Device Pixel Ratio) Handling
function getDPR(element: Element): number { if (typeof window === 'undefined') return 1; const win = element.ownerDocument.defaultView || window; return win.devicePixelRatio || 1;}function roundByDPR(element: Element, value: number) { const dpr = getDPR(element); return Math.round(value * dpr) / dpr;}Why round by DPR?
On high-DPI screens, CSS pixels map to multiple physical pixels. Positioning at fractional CSS pixels can cause the element to straddle physical pixel boundaries, causing blurriness.
DPR = 2 (each CSS pixel = 2x2 physical pixels)Without rounding (value = 150.3):┌──┬──┬──┬──┬──┐│ │ │▒▒│ │ │ ← Partial pixel coverage = BLUR└──┴──┴──┴──┴──┘With rounding (snaps to 150.5):┌──┬──┬──┬──┬──┐│ │ │██│ │ │ ← Full pixel coverage = SHARP└──┴──┴──┴──┴──┘Why willChange only on high DPR?
...(getDPR(elements.floating) >= 1.5 && {willChange: 'transform'}),- High-DPR screens benefit most from GPU acceleration
will-changehas memory overhead- Low-DPR screens don't need the performance hint
Complete Data Flow
Flowchart
Full Implementation
Here's the complete source code with the patterns we discussed in action:
import {computePosition} from '@floating-ui/dom';import * as React from 'react';import * as ReactDOM from 'react-dom';import useModernLayoutEffect from 'use-isomorphic-layout-effect';import type { ComputePositionConfig, ReferenceType, UseFloatingData, UseFloatingOptions, UseFloatingReturn,} from './types';import {deepEqual} from './utils/deepEqual';import {getDPR} from './utils/getDPR';import {roundByDPR} from './utils/roundByDPR';import {useLatestRef} from './utils/useLatestRef';export function useFloating<RT extends ReferenceType = ReferenceType>( options: UseFloatingOptions = {},): UseFloatingReturn<RT> { const { placement = 'bottom', strategy = 'absolute', middleware = [], platform, elements: {reference: externalReference, floating: externalFloating} = {}, transform = true, whileElementsMounted, open, } = options; // Position data state - drives the UI const [data, setData] = React.useState<UseFloatingData>({ x: 0, y: 0, strategy, placement, middlewareData: {}, isPositioned: false, }); // Middleware comparison (deep equality check) const [latestMiddleware, setLatestMiddleware] = React.useState(middleware); if (!deepEqual(latestMiddleware, middleware)) { setLatestMiddleware(middleware); } // DUAL STATE + REF PATTERN: State triggers effects, refs give current values const [_reference, _setReference] = React.useState<RT | null>(null); const [_floating, _setFloating] = React.useState<HTMLElement | null>(null); const setReference = React.useCallback((node: RT | null) => { if (node !== referenceRef.current) { referenceRef.current = node; // Immediate for async callbacks _setReference(node); // Triggers effects } }, []); const setFloating = React.useCallback((node: HTMLElement | null) => { if (node !== floatingRef.current) { floatingRef.current = node; _setFloating(node); } }, []); const referenceEl = (externalReference || _reference) as RT | null; const floatingEl = externalFloating || _floating; // Refs for always-current values const referenceRef = React.useRef<RT | null>(null); const floatingRef = React.useRef<HTMLElement | null>(null); const dataRef = React.useRef(data); // LATEST REF PATTERN: Avoid stale closures without adding dependencies const hasWhileElementsMounted = whileElementsMounted != null; const whileElementsMountedRef = useLatestRef(whileElementsMounted); const platformRef = useLatestRef(platform); const openRef = useLatestRef(open); // THE UPDATE FUNCTION: Bridge between async computePosition and React const update = React.useCallback(() => { if (!referenceRef.current || !floatingRef.current) { return; } const config: ComputePositionConfig = { placement, strategy, middleware: latestMiddleware, }; if (platformRef.current) { config.platform = platformRef.current; } computePosition(referenceRef.current, floatingRef.current, config).then( (data) => { const fullData = { ...data, isPositioned: openRef.current !== false, }; // Guards: mounted check + deep equality to prevent loops if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) { dataRef.current = fullData; // flushSync for immediate updates during scroll/resize ReactDOM.flushSync(() => { setData(fullData); }); } }, ); }, [latestMiddleware, placement, strategy, platformRef, openRef]); // Reset isPositioned when closing useModernLayoutEffect(() => { if (open === false && dataRef.current.isPositioned) { dataRef.current.isPositioned = false; setData((data) => ({...data, isPositioned: false})); } }, [open]); // Track mounted state for async safety const isMountedRef = React.useRef(false); useModernLayoutEffect(() => { isMountedRef.current = true; return () => { isMountedRef.current = false; }; }, []); // MAIN EFFECT: Connect elements and set up subscriptions useModernLayoutEffect(() => { if (referenceEl) referenceRef.current = referenceEl; if (floatingEl) floatingRef.current = floatingEl; if (referenceEl && floatingEl) { if (whileElementsMountedRef.current) { // Return cleanup function from whileElementsMounted (e.g., autoUpdate) return whileElementsMountedRef.current(referenceEl, floatingEl, update); } update(); } }, [ referenceEl, floatingEl, update, whileElementsMountedRef, hasWhileElementsMounted, ]); // Memoized return values const refs = React.useMemo( () => ({ reference: referenceRef, floating: floatingRef, setReference, setFloating, }), [setReference, setFloating], ); const elements = React.useMemo( () => ({reference: referenceEl, floating: floatingEl}), [referenceEl, floatingEl], ); // CSS OUTPUT: Transform-based positioning with DPR handling const floatingStyles = React.useMemo(() => { const initialStyles = { position: strategy, left: 0, top: 0, }; if (!elements.floating) { return initialStyles; } const x = roundByDPR(elements.floating, data.x); const y = roundByDPR(elements.floating, data.y); if (transform) { return { ...initialStyles, transform: `translate(${x}px, ${y}px)`, ...(getDPR(elements.floating) >= 1.5 && {willChange: 'transform'}), }; } return { position: strategy, left: x, top: y, }; }, [strategy, transform, elements.floating, data.x, data.y]); return React.useMemo( () => ({ ...data, update, refs, elements, floatingStyles, }), [data, update, refs, elements, floatingStyles], );}Key Takeaways
-
Dual state + ref pattern solves the tension between triggering effects and accessing current values in async callbacks
-
useLatestRef keeps values fresh in callbacks without adding unstable dependencies
-
flushSync ensures immediate rendering during rapid updates like scrolling
-
isMountedRef guards against setState on unmounted components after async operations
-
isPositioned enables smooth animations by distinguishing initial placement from subsequent updates
-
Transform positioning with DPR rounding provides crisp, performant rendering
-
whileElementsMounted abstracts the subscription lifecycle for continuous position updates
These patterns aren't unique to Floating UI - they're broadly applicable solutions for bridging imperative/async APIs with React's declarative model.
Series Navigation
This article is part of a deep dive series on Floating UI:
| Article | Topic | Key Concepts |
|---|---|---|
| Part 1: Coordinate System | How positions are calculated | Browser coordinates, placements, axes, computeCoordsFromPlacement |
| Part 2: Middleware Deep Dive | How positions are adjusted | offset, detectOverflow, shift, flip, pipeline architecture |
| Part 3: useFloating (this article) | How it works in React | Dual state/ref, flushSync, whileElementsMounted, floatingStyles |