- explain what batching is and why it matters
- build a tiny, reusable Batcher<T> utility
- show a minimal React example that uses it
What is batching?
- analytics or telemetry events
- autosave or form-change sync
- reordering items (e.g., drag-and-drop) that produce many quick updates
How batching works
- you have a queue to hold items
- you have a timer (the "window") that resets whenever a new item arrives
- when the timer expires, you flush: send the accumulated items and clear the queue
Implementation
Ts
React usage (minimal)
Tsx
When to use batching
- when many fast, small updates would otherwise spam your API
- when slight delay (e.g., up to 1-5 seconds) is acceptable
- when you want to reduce costs by shrinking request count
Tips and trade-offs
- choose windowMs based on acceptable UX delay and event rate
- flush on teardown (component unmount, page hide) so you do not lose work
- decide what happens on onFlush failure (retry, drop, or store locally)
- keep items small; avoid building huge batches that can time out
