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(dashboard): defer layout commits until drag/resize stops (#65539)

Matt Pua07caea84433b
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
index 01f8f76ce60b..3ca460d9763c 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
@@ -3,7 +3,7 @@ import './InsightCard.scss'
import { useMergeRefs } from '@floating-ui/react'
import clsx from 'clsx'
import { BindLogic, useValues } from 'kea'
-import React, { useState } from 'react'
+import React, { useMemo, useState } from 'react'
import { LayoutItem } from 'react-grid-layout'
import { useInView } from 'react-intersection-observer'
@@ -66,6 +66,8 @@ export interface InsightCardProps extends Resizeable {
timedOut?: boolean
/** Whether the editing controls should be enabled or not. */
showEditingControls?: boolean
+ /** While this tile is being resized: unmount the viz so the chart doesn't redraw on every frame. */
+ isResizing?: boolean
/** Whether the controls for showing details should be enabled or not. */
showDetailsControls?: boolean
/** Layout of the card on a grid. */
@@ -123,6 +125,7 @@ function InsightCardInternal(
timedOut,
highlighted,
showResizeHandles,
+ isResizing,
showEditingControls,
showDetailsControls,
updateColor,
@@ -170,13 +173,17 @@ function InsightCardInternal(
const mergedRefs = useMergeRefs([ref, inViewRef])
const { theme } = useValues(themeLogic)
- const insightLogicProps: InsightLogicProps = {
- dashboardItemId: insight.short_id,
- dashboardId: dashboardId,
- cachedInsight: insight,
- loadPriority,
- doNotLoad,
- }
+ // Stable reference so the memoized viz below isn't invalidated on every grid re-render.
+ const insightLogicProps: InsightLogicProps = useMemo(
+ () => ({
+ dashboardItemId: insight.short_id,
+ dashboardId: dashboardId,
+ cachedInsight: insight,
+ loadPriority,
+ doNotLoad,
+ }),
+ [insight, dashboardId, loadPriority, doNotLoad]
+ )
const { insightLoading } = useValues(insightLogic(insightLogicProps))
const { insightDataLoading } = useValues(insightDataLogic(insightLogicProps))
@@ -237,6 +244,40 @@ function InsightCardInternal(
return null
})()
+ // Memoize the viz so the (expensive) chart subtree isn't reconciled when the card re-renders only because
+ // react-grid-layout reflowed it — e.g. while a sibling tile is dragged or resized. React reuses the cached
+ // element when these inputs are unchanged, so only the tiles whose data actually changed redraw.
+ const vizContent = useMemo(() => {
+ if (isResizing) {
+ // Skip the chart while resizing — keeping it mounted would redraw the canvas on every frame as the
+ // tile's dimensions change. Remounts from cached results once resizing stops.
+ return <div className="InsightCard__viz" />
+ }
+ if (!isVisible) {
+ return null
+ }
+ return (
+ <div className="InsightCard__viz">
+ {BlockingEmptyState ? (
+ BlockingEmptyState
+ ) : (
+ <Query
+ query={insight.query}
+ cachedResults={insight}
+ context={{
+ insightProps: insightLogicProps,
+ }}
+ readOnly
+ embedded
+ inSharedMode={placement === DashboardPlacement.Public}
+ variablesOverride={variablesOverride}
+ editMode={false}
+ />
+ )}
+ </div>
+ )
+ }, [isResizing, isVisible, BlockingEmptyState, insight, insightLogicProps, variablesOverride, placement])
+
return (
<div
className={clsx(
@@ -281,26 +322,7 @@ function InsightCardInternal(
surveyOpportunity={surveyOpportunity}
onDragHandleMouseDown={onDragHandleMouseDown}
/>
- {isVisible ? (
- <div className="InsightCard__viz">
- {BlockingEmptyState ? (
- BlockingEmptyState
- ) : (
- <Query
- query={insight.query}
- cachedResults={insight}
- context={{
- insightProps: insightLogicProps,
- }}
- readOnly
- embedded
- inSharedMode={placement === DashboardPlacement.Public}
- variablesOverride={variablesOverride}
- editMode={false}
- />
- )}
- </div>
- ) : null}
+ {vizContent}
</BindLogic>
</ErrorBoundary>
{showResizeHandles && <DashboardResizeHandles />}
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index cc34b56d5873..8104c4194e77 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -85,11 +85,18 @@ export function DashboardItems(): JSX.Element {
? null
: getBestSurveyOpportunityFunnel(tiles || [], surveyLinkedInsights)
- const resizingItemRef = useRef<any>(null)
+ // Tile currently being resized. Its viz is unmounted for the duration of the gesture so the chart doesn't
+ // redraw on every frame as the tile's dimensions change — the dominant cost that makes resizing feel laggy.
+ const [resizingTileId, setResizingTileId] = useState<string | null>(null)
const [containerHeight, setContainerHeight] = useState<number | undefined>(undefined)
// cannot click links when dragging and 250ms after
const isDragging = useRef(false)
+ // While a drag/resize is in progress the grid drives itself from its own internal state and ignores the
+ // `layouts` prop, so pushing layout updates to the store mid-gesture only triggers expensive full re-renders
+ // (every InsightCard) that make the dragged tile lag the cursor. Stash the latest layout and commit once on stop.
+ const interactionInProgress = useRef(false)
+ const pendingLayouts = useRef<Partial<Record<DashboardLayoutSize, Layout>> | null>(null)
const dragEndTimeout = useRef<number | null>(null)
const scrollAnimationRef = useRef<number | null>(null)
const scrollContainerRef = useRef<HTMLElement | null>(null)
@@ -269,13 +276,27 @@ export function DashboardItems(): JSX.Element {
const handleLayoutChange = useCallback(
(_: unknown, newLayouts: Partial<Record<DashboardLayoutSize, Layout>>) => {
- if (layoutEditMode) {
- updateLayouts(newLayouts)
+ if (!layoutEditMode) {
+ return
+ }
+ // Defer commits while dragging/resizing — the final layout is flushed on gesture stop.
+ if (interactionInProgress.current) {
+ pendingLayouts.current = newLayouts
+ return
}
+ updateLayouts(newLayouts)
},
[layoutEditMode, updateLayouts]
)
+ const flushPendingLayouts = useCallback(() => {
+ interactionInProgress.current = false
+ if (pendingLayouts.current) {
+ updateLayouts(pendingLayouts.current)
+ pendingLayouts.current = null
+ }
+ }, [updateLayouts])
+
const handleWidthChange = useCallback(
(containerWidth: number, _: unknown, newCols: number) => {
updateContainerWidth(containerWidth, newCols)
@@ -283,18 +304,25 @@ export function DashboardItems(): JSX.Element {
[updateContainerWidth]
)
+ const handleResizeStart = useCallback(() => {
+ interactionInProgress.current = true
+ }, [])
+
const handleResize = useCallback((_layout: any, _oldItem: any, newItem: any) => {
- resizingItemRef.current = newItem
+ // Setting state to the same id bails out of re-rendering, so this only re-renders once per gesture.
+ setResizingTileId(newItem.i)
}, [])
const handleResizeStop = useCallback(() => {
- resizingItemRef.current = null
+ setResizingTileId(null)
+ flushPendingLayouts()
if (dashboard?.id) {
reportDashboardTileRepositioned(dashboard.id, 'resized', effectiveZoom)
}
- }, [dashboard?.id, reportDashboardTileRepositioned, effectiveZoom])
+ }, [dashboard?.id, reportDashboardTileRepositioned, effectiveZoom, flushPendingLayouts])
const handleDragStart = useCallback(() => {
+ interactionInProgress.current = true
scrollContainerRef.current = document.getElementById('main-content')
scrollContainerRectRef.current = scrollContainerRef.current?.getBoundingClientRect() ?? null
}, [])
@@ -356,10 +384,11 @@ export function DashboardItems(): JSX.Element {
dragEndTimeout.current = window.setTimeout(() => {
isDragging.current = false
}, 250)
+ flushPendingLayouts()
if (dashboard?.id) {
reportDashboardTileRepositioned(dashboard.id, 'moved', effectiveZoom)
}
- }, [dashboard?.id, reportDashboardTileRepositioned, effectiveZoom])
+ }, [dashboard?.id, reportDashboardTileRepositioned, effectiveZoom, flushPendingLayouts])
return (
<div className="dashboard-items-wrapper" ref={containerRef as RefObject<HTMLDivElement>}>
@@ -397,6 +426,7 @@ export function DashboardItems(): JSX.Element {
onWidthChange={handleWidthChange}
breakpoints={BREAKPOINTS}
cols={BREAKPOINT_COLUMN_COUNTS}
+ onResizeStart={handleResizeStart}
onResize={handleResize}
onResizeStop={handleResizeStop}
onDragStart={handleDragStart}
@@ -455,6 +485,7 @@ export function DashboardItems(): JSX.Element {
showDetailsControls={showDetailsControls}
placement={placement}
loadPriority={smLayout ? smLayout.y * 1000 + smLayout.x : undefined}
+ isResizing={resizingTileId === tile.id.toString()}
filtersOverride={effectiveEditBarFilters}
variablesOverride={effectiveDashboardVariableOverrides}
// :HACKY: The two props below aren't actually used in the component, but are needed to trigger a re-render