Skip to content

Batching UI updates

Collecting many small state changes or DOM writes and applying them once per frame or tick, so a burst of events costs one render instead of hundreds. The craft is choosing the flush point and what must not wait.

On this page

What it is

Batching groups several updates into a single render pass. The browser normally produces a frame in this order: JavaScript runs, then styles are calculated, then layout, then paint. When code applies updates one at a time, each can trigger its own share of that work, and a burst of events from a socket, a pointer or a loop can turn into many passes where one would do. A batch collects those updates in memory and hands them to the renderer at one chosen moment, the flush point.

There are three common flush points. A microtask, queued with queueMicrotask or a resolved promise, runs after the current script finishes and before the browser gets a chance to update rendering, so it groups everything that happened inside one event into one write. A requestAnimationFrame callback runs before the next repaint, and the browser calls it at roughly the display's refresh rate, 60 times a second on the most common screens, so it is the natural cadence for anything visual that keeps changing. A framework tick is the batching your UI library does for you: React groups state updates into one re-render, and Vue buffers DOM updates until its next tick so each component updates once however many values changed.

ts
type Flush<T> = (batch: Map<string, T>) => void;

function frameBatcher<T>(flush: Flush<T>) {
  const pending = new Map<string, T>();
  let scheduled = false;

  return (key: string, value: T) => {
    pending.set(key, value); // the latest value per key wins
    if (scheduled) return;
    scheduled = true;
    requestAnimationFrame(() => {
      scheduled = false;
      const batch = new Map(pending);
      pending.clear();
      flush(batch); // one state update per frame
    });
  };
}

const pushPrice = frameBatcher<number>((batch) => {
  setPrices((prev) => ({ ...prev, ...Object.fromEntries(batch) }));
});

socket.onmessage = (event) => {
  const { symbol, price } = JSON.parse(event.data);
  pushPrice(symbol, price);
};

Framework batching has edges worth knowing. Before React 18, React batched state updates inside its own event handlers, and updates made in a promise, a timeout or a native listener each caused their own render. React 18 with createRoot batches updates wherever they come from. The team notes that for a discrete event such as a click or a key press, the DOM is updated before the next such event is handled, which is why a submit button that disables itself in state is not clicked twice. flushSync from react-dom forces the pending updates to apply at once; its documentation calls it uncommon, warns it can hurt performance, and notes it may make a pending Suspense boundary show its fallback.

When to use it

Reach for a frame-aligned batch when a source produces updates faster than the screen can show them: a WebSocket feed of prices or presence, tokens from a streaming response, pointer moves driving a cursor or a drag, a loop inserting many rows. The screen repaints at its refresh rate, so applying 2,000 updates a second buys nothing visible over applying 60 coalesced ones; the extra passes are wasted work unless each intermediate state matters. Use requestAnimationFrame as the flush point and let the callback schedule nothing itself: the next incoming message schedules the next flush. For the token case see Streaming responses in the UI.

Batch DOM reads separately from DOM writes. Reading a geometry property such as offsetHeight after a style change forces the browser to run layout early so it can answer; doing that in a loop, read then write then read, is layout thrashing. The fix is ordering: read all the values you need first, while the browser can still use the previous frame's layout, then make all the writes. Layout cost also tends to grow with the size of the DOM, which is a second reason to apply a burst of insertions in one go.

Use a microtask when several callers in the same event each ask for the same kind of work and you want one result. MDN's example queues messages into an array and, on the first push, schedules a microtask that sends the whole array as one request; later pushes in the same task land in the array before the microtask runs. The same shape groups several store dispatches into one notification to subscribers.

When not to

Don't delay feedback to a direct action. The character someone typed, the pressed look of a button, a focus ring, a menu opening: these should land in the very next frame, and routing them through a buffer that waits for a timer adds lag the person feels. Interaction latency, from the input to the frame that shows its result, is what the Interaction to Next Paint metric measures. Frameworks already handle the common case: React applies a click's updates before it handles the next click, so you rarely need to do anything here but avoid adding a layer.

Don't add your own frame batch around a framework's state setter for updates that already arrive inside one event. React 18 roots and Vue each merge the state changes made in one tick into a single render, so for a click handler that sets three values a second layer adds a frame of delay and one more place for stale values. Manual batching earns its keep when updates arrive in separate tasks, such as one socket message per task: the framework batches within a task, so each task can start its own render. Put it in the data layer that receives those messages, where it decides how many times per frame the store changes at all.

Skip batching when the next line of code needs the DOM to be current, for example handing the page to a print dialog or a third-party widget that measures what you just rendered. That is the case flushSync exists for, with the cost its documentation describes: slower, and able to surface Suspense fallbacks. Use it for that one spot, not as a general habit.

Be careful with requestAnimationFrame as the flush point when the tab may be hidden. Most browsers pause these callbacks in background tabs and hidden iframes to save battery, so a buffer that waits on the next frame stops draining while the feed keeps arriving. A buffer that coalesces over a fixed set of keys stays bounded; an accumulating one, or one that keeps seeing new keys, grows for as long as the tab is hidden. Cap it, drop to a timer while hidden, or pause the subscription.

Compared

Flush pointWhen it runsReach for it whenWhen the other option is better

Apply immediately

Inside the event handler

One update per user action, and the person is waiting on it

Under a burst, each write can trigger its own style and layout work

Microtask (queueMicrotask, a resolved promise)

After the current script, before the browser may render

Several calls in one task should become one write or one request

A stream of socket messages arrives as separate tasks, so each still renders

requestAnimationFrame

Before the next repaint, about once per display refresh

Continuous visual output: feeds, cursors, progress

Paused in hidden tabs by most browsers, and adds up to a frame of delay to direct feedback

Timer (setTimeout each N ms)

As a task, after at least N ms

You want fewer updates than the refresh rate, such as a log that redraws a few times a second

Not aligned to frames, and a large N reads as lag

Framework batching (React 18 root, Vue tick)

At the end of the event or tick

Ordinary state updates in components

It doesn't reduce how many messages your handler processes; flushSync to opt out has a cost

In a picture

latest persymbolSocket messagesHandlerPending map

Step 1 of 3

Messages arrive faster than frames

A socket delivers price updates for 50 symbols, thousands per second. The handler writes each one into a map keyed by symbol, so a symbol that changed ten times since the last flush holds one value.

How to say it in an interview

The common mistake

Quiz

A ticker receives about 2,000 price updates a second for 50 symbols, shown on a 60 Hz display. What should a per-frame batch do?
In a React 18 click handler you set state, then immediately read the element's height and get the old value. Why?
A chat view appends each incoming message to a buffer and flushes it in a requestAnimationFrame callback. The tab sits hidden for twenty minutes. What happens?
A loop sets the width of 200 paragraphs to match box.offsetWidth, reading it inside each iteration. Rendering stutters. What is the fix?

Related

Sources

  1. MDN: Window: requestAnimationFrame() method
  2. MDN: Using microtasks in JavaScript with queueMicrotask()
  3. web.dev: Avoid large, complex layouts and layout thrashing
  4. React 18 Working Group: Automatic batching for fewer renders in React 18
  5. React reference: flushSync
  6. Vue.js guide: Reactivity Fundamentals (DOM Update Timing)
Sign in to report a mistake