Blogs

Realtime collaboration series · Part 5 of 5

Cursors lag behind while you pan

You drag the board to look at another corner. Your teammates’ cursors and the little comment pins slide a few pixels behind, then snap back into place. It only lasts a frame, but on a big screen it makes the whole app feel loose.

1The problem: two layers, two clocks

A collaborative canvas is usually two layers stacked on top of each other:

  • The canvas, drawn directly (HTML canvas, WebGL or SVG) the moment the viewport changes.
  • The overlays: other people’s cursors, comment pins, selection boxes, name tags. These are often normal UI components, for example in React, because they need text, menus and clicks.

Both layers depend on the same viewport. If the canvas uses the new viewport in this frame and the overlays only catch up in the next one, every overlay is drawn in the wrong place for one frame. While you pan, that happens every frame, and the overlays seem to swim.

Screens · animated
Overlay updated a frame laterOverlay in the same frameYour screen, panningYour screen, panningLogin3BobLogin3Bobpin and cursor swim behind the shapeeverything moves as one
Slowed down. Same pan, same data: the only difference is whether the overlays are updated in the same frame as the canvas.

Why the overlays are late

UI frameworks are built to batch work. React, for example, collects state updates and renders them together a little later, and it treats a stream of wheel or pointer events as lower priority than a click. That is usually a great trade: fewer renders, smoother typing. But it means the browser can paint the freshly drawn canvas before the overlay update has been committed.

Frames · animated
frame 1frame 2frame 3frame 4Canvasview 0view 1view 2view 3Overlay, rendered laterview 0view 0view 1view 2Overlay, flushed nowview 0view 1view 2view 3orange: the screen shows two different views at once
One frame behind is invisible when nothing moves, and obvious when everything does.

2The solution: commit both in the same frame

The rule is simple: whatever draws the canvas must also update the overlays before the browser paints. In React, the narrow tool for this is flushSync: it renders and commits the updates inside its callback immediately, instead of later.

Two more details keep it cheap. Collapse many input events into one update per frame with requestAnimationFrame. And flush only the viewport update that the overlays need, not the rest of the app.

Key ideaThings that must move together must be committed together. Batching is right for most UI, and wrong for layers that have to line up pixel for pixel.
Options
A · Flush overlays nowCommit the overlay update synchronously, in thesame frame the canvas is drawnSmall change; keeps React componentsB · Skip React per frameOverlays read the viewport from a store and settheir own CSS transformFastest; more manual codeC · One transform for bothPut overlays inside the same transformed layer asthe canvasSimplest; but labels scale with zoomD · Draw overlays on the canvasCursors and pins are pixels, drawn in the samepassAlways in step; no DOM, harder to style
Flushing is the smallest change to an existing app. The others avoid the problem by not involving the framework at all on every frame.

3Example code

A viewport store that draws the canvas and flushes overlays in the same animation frame, and a comment pin that follows it. The pin converts board coordinates to screen pixels using the viewport it received.

viewport.tsx
import { flushSync } from 'react-dom'

type Viewport = { x: number; y: number; zoom: number }
let viewport: Viewport = { x: 0, y: 0, zoom: 1 }
let next: Viewport | null = null
const listeners = new Set<(v: Viewport) => void>()

// Wheel and pointer events can fire many times per frame: keep the newest.
function onWheel(e: WheelEvent) {
  next = zoomAround(next ?? viewport, e.clientX, e.clientY, e.deltaY)
  requestAnimationFrame(commitFrame)       // one commit per frame
}

function commitFrame() {
  if (!next) return
  viewport = next
  next = null
  drawCanvas(viewport)                     // the canvas changes now…
  flushSync(() => {                        // …so the overlays must too
    listeners.forEach((fn) => fn(viewport))
  })
}

// An overlay: a comment pin anchored to a point on the board.
function CommentPin({ at }: { at: { x: number; y: number } }) {
  const [v, setV] = useState(viewport)
  useEffect(() => {
    listeners.add(setV)
    return () => { listeners.delete(setV) }
  }, [])
  const left = (at.x - v.x) * v.zoom      // board → screen
  const top = (at.y - v.y) * v.zoom
  return <div className="pin" style={{ transform: `translate(${left}px, ${top}px)` }} />
}

Without flushSync, setV would schedule the pins to update a little later, and the canvas drawn on the line before would be painted first. With it, every pin is placed before the frame ends.

4In practice: a design tool

  • Cursors, comment pins and preview panels all had the same symptom and the same fix, because they all anchor UI to points on the board.
  • Keep the flushed tree small. flushSync renders synchronously, so a large component tree inside it can make panning stutter. Subscribe only the overlay components, not the page.
  • Measure with a recording. The bug is one frame long, so a slow-motion screen recording or the browser’s performance panel shows it much better than your eyes.
  • Remote cursors from part 4 are overlays too. Their board position comes over the network; their screen position must still follow your own viewport in the same frame.

5Pros and cons

For flushing overlay updates synchronously:

Pros

  • Fixes the lag with a few lines in one place
  • Overlays stay normal components with text, menus and clicks
  • Easy to reason about: canvas and overlays always share one viewport

Cons

  • Gives up batching for those updates, so heavy overlays cost more per frame
  • Easy to overuse; flushing large parts of the app makes everything slower
  • React warns against calling it during rendering, so it must live in event or frame callbacks

6Alternatives

OptionHow it worksYou gainYou pay
Direct DOM updatesOverlays subscribe to the viewport and set style.transform through a ref, bypassing React on each frameNo React render per frame, so it’s the fastestTwo sources of truth: your code must keep the DOM positions in sync with React state, and a missed update shows as a misplaced overlay
Shared CSS transformPut overlays inside the same transformed container as the canvasOne transform moves canvas and overlays together, with almost no codeOverlays scale with zoom (labels get tiny or huge) unless you counter-scale each one
Draw on the canvasRender cursors and pins as part of the canvas passAlways in the same frame as the canvasNo DOM: no text selection, no normal clicks or hover, nothing for screen readers; you hit-test and redraw yourself
Accept the lagLeave overlays batchedNo work at allOverlays trail the canvas by a frame while panning

7Conclusion

Key ideaOverlays that sit on a moving canvas must be updated in the same frame as the canvas. Use flushSync narrowly for the overlay update, or move per-frame positioning outside the framework.

That is the end of the series. Live channels carry edits, reliable delivery makes them arrive, conflict rules make screens agree, presence shows who is behind them, and overlays keep it all lined up on screen.