Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(frontend): make useAnimatedPresence enter transition deterministic (#74128)

Juraj Majerik45778172f21c
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index dd4a361df506..16ca8d14d289 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5573,7 +5573,7 @@ snapshots:
scenes-app-dashboards--show-across-viewports--narrow--dark:
hash: v1.k794b7964.e919c4955d7113170ab00269c5f628c318afe14f26dc8aafb046b172e17f362e.YDXD84rrb2KR1I36pHMxEsGZ0sN0os_cBBdNIf89Pu8
scenes-app-dashboards--show-across-viewports--narrow--light:
- hash: v1.k794b7964.a46d840722e971910236d6fcd8a8f69e0b1db5ee9d472d62055b02d6569f7a99.kHEdVPNUm5DRKSlMFS12SLKf1TyChQJZKKuZ2PKvtfA
+ hash: v1.k794b7964.e6a99deaafbd0220dbe5b084e809b2c09113f273c108b48ec57b6e37720edd52.5OqJSo3vD5pzHttmCjtC1mWKKtfw54yjZbcnkl6WnOA
scenes-app-dashboards--show-across-viewports--superwide--dark:
hash: v1.k794b7964.9948b52cf842206c1584057a6a16b8caed7a32d95f103dbea07089a02df75a53.AuXGqOvw-P-XuzOL2Zl-BkBPb1-Q3R1949f5-IkTjZA
scenes-app-dashboards--show-across-viewports--superwide--light:
diff --git a/frontend/src/lib/hooks/useAnimatedPresence.test.ts b/frontend/src/lib/hooks/useAnimatedPresence.test.ts
index 72433be9ba77..2584808eb9ab 100644
--- a/frontend/src/lib/hooks/useAnimatedPresence.test.ts
+++ b/frontend/src/lib/hooks/useAnimatedPresence.test.ts
@@ -71,6 +71,20 @@ describe('useAnimatedPresence', () => {
expect(result.current).toEqual({ rendered: true, shown: true })
})
+ it('flips shown synchronously via a reflow when given a ref, without waiting for a frame', () => {
+ const ref = { current: document.createElement('div') }
+ const { result, rerender } = renderHook(({ isIn }) => useAnimatedPresence(isIn, 200, ref), {
+ initialProps: { isIn: false },
+ })
+ expect(result.current).toEqual({ rendered: false, shown: false })
+
+ // The layout effect forces a reflow and flips shown in the same commit —
+ // no RAF is scheduled, so the enter can't be lost to paint coalescing.
+ rerender({ isIn: true })
+ expect(result.current).toEqual({ rendered: true, shown: true })
+ expect(rafCallbacks).toHaveLength(0)
+ })
+
it('flips shown immediately on exit and unrenders after the duration', () => {
const { result, rerender } = renderHook(({ isIn }) => useAnimatedPresence(isIn, 200), {
initialProps: { isIn: true },
diff --git a/frontend/src/lib/hooks/useAnimatedPresence.ts b/frontend/src/lib/hooks/useAnimatedPresence.ts
index 47d9fd08ad0b..15b92984ac07 100644
--- a/frontend/src/lib/hooks/useAnimatedPresence.ts
+++ b/frontend/src/lib/hooks/useAnimatedPresence.ts
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from 'react'
+import { RefObject, useEffect, useLayoutEffect, useRef, useState } from 'react'
export interface AnimatedPresenceState {
rendered: boolean
@@ -17,8 +17,19 @@ export interface AnimatedPresenceState {
*
* `rendered !== shown` while a transition is mid-flight, so call sites that
* need an `aria-busy`-style signal can derive it from those two booleans.
+ *
+ * Pass `ref` (pointing at the transitioning element) when the enter animation
+ * must be reliable. Without it the flip to `shown` is deferred with rAF, which
+ * only *usually* lets the pre-transition styles paint first — under load the
+ * mount and the flip can coalesce into one paint and the enter transition is
+ * skipped. With a ref, the flip forces a synchronous reflow instead, which
+ * deterministically records the hidden state as the transition's start value.
*/
-export function useAnimatedPresence(isIn: boolean, durationMs: number): AnimatedPresenceState {
+export function useAnimatedPresence(
+ isIn: boolean,
+ durationMs: number,
+ ref?: RefObject<HTMLElement | null>
+): AnimatedPresenceState {
const [rendered, setRendered] = useState(isIn)
const [shown, setShown] = useState(isIn)
const renderedRef = useRef(rendered)
@@ -27,20 +38,7 @@ export function useAnimatedPresence(isIn: boolean, durationMs: number): Animated
useEffect(() => {
if (isIn) {
setRendered(true)
- // Defer the visibility flip two frames so the browser paints the
- // pre-transition (hidden) styles first. `setRendered` runs from a
- // passive effect (after paint), so a single RAF fires in the same
- // frame as the mount's paint — the browser coalesces both states
- // into one paint and the enter transition never runs. The extra
- // frame guarantees the hidden state paints before `shown` flips.
- let innerRaf = 0
- const outerRaf = window.requestAnimationFrame(() => {
- innerRaf = window.requestAnimationFrame(() => setShown(true))
- })
- return () => {
- window.cancelAnimationFrame(outerRaf)
- window.cancelAnimationFrame(innerRaf)
- }
+ return
}
if (!renderedRef.current) {
return
@@ -50,5 +48,35 @@ export function useAnimatedPresence(isIn: boolean, durationMs: number): Animated
return () => window.clearTimeout(timer)
}, [isIn, durationMs])
+ // Flip `shown` on only once the hidden element is mounted, and make the
+ // browser commit that hidden state as the transition's start value first —
+ // otherwise the mount and the flip land in one paint and the enter
+ // transition never runs.
+ useLayoutEffect(() => {
+ if (!isIn || !rendered || shown) {
+ return
+ }
+ const node = ref?.current
+ if (node) {
+ // Force a synchronous layout so the hidden styles are the recorded
+ // start value; the flip below then animates from them. Deterministic,
+ // unlike frame-counting.
+ void node.offsetHeight
+ setShown(true)
+ return
+ }
+ // Headless fallback (no node to reflow): defer two frames so the hidden
+ // state has a chance to paint before the flip. Best-effort — pass a ref
+ // when the transition must be reliable.
+ let innerRaf = 0
+ const outerRaf = window.requestAnimationFrame(() => {
+ innerRaf = window.requestAnimationFrame(() => setShown(true))
+ })
+ return () => {
+ window.cancelAnimationFrame(outerRaf)
+ window.cancelAnimationFrame(innerRaf)
+ }
+ }, [isIn, rendered, shown, ref])
+
return { rendered, shown }
}
diff --git a/frontend/src/lib/lemon-ui/LemonCollapse/LemonCollapse.tsx b/frontend/src/lib/lemon-ui/LemonCollapse/LemonCollapse.tsx
index 72fc5eaa27ef..f48e1d47da3a 100644
--- a/frontend/src/lib/lemon-ui/LemonCollapse/LemonCollapse.tsx
+++ b/frontend/src/lib/lemon-ui/LemonCollapse/LemonCollapse.tsx
@@ -1,7 +1,7 @@
import './LemonCollapse.scss'
import clsx from 'clsx'
-import React, { ReactNode, useEffect, useMemo, useState } from 'react'
+import React, { ReactNode, useEffect, useMemo, useRef, useState } from 'react'
import useResizeObserver from 'use-resize-observer'
import { IconCollapse, IconExpand } from '@posthog/icons'
@@ -131,7 +131,8 @@ function LemonCollapsePanel({
onHeaderClick,
}: LemonCollapsePanelProps): JSX.Element {
const { height: contentHeight, ref: contentRef } = useResizeObserver({ box: 'border-box' })
- const { rendered, shown } = useAnimatedPresence(isExpanded, 200)
+ const bodyRef = useRef<HTMLDivElement>(null)
+ const { rendered, shown } = useAnimatedPresence(isExpanded, 200, bodyRef)
const { headerChildren, headerProps } = useMemo((): HeaderDefinition => {
if (header && typeof header === 'object' && 'children' in header) {
@@ -174,6 +175,7 @@ function LemonCollapsePanel({
{rendered && (
<div
+ ref={bodyRef}
className="LemonCollapsePanel__body"
// eslint-disable-next-line react/forbid-dom-props
style={{ height: shown ? contentHeight : 0 }}