Real-time applications are great.
You make a change somewhere, and the UI updates automatically. You don't have to manually refresh the page or write a bunch of synchronization logic. This is one of the things I really like about Convex.
But while working with reactive queries, I ran into an interesting problem:
What happens when the latest data is not what the user should see right now?
This sounds a little strange at first. Isn't showing the latest data the whole point of a reactive query?
Sometimes, yes.
But sometimes, automatically updating the UI can actually make the experience worse.
That led me to build a small React hook called useBufferedState.
The Problem
Imagine you're building a reading platform.
Users can publish articles, and the home page shows a feed of articles from other users.
A simplified version might look like this:
const posts = useQuery(api.posts.list);Then we render the posts:
{posts?.map((post) => (
<PostCard key={post._id} post={post} />
))}Nothing unusual here.
Convex gives us a reactive query, so whenever the underlying data changes, the query updates and the UI re-renders.
That's exactly what we want—until the user is in the middle of something.
Imagine you're reading a feed.
You scroll down, find an interesting article, and start reading:
┌─────────────────────────┐
│ Article A │
│ │
│ Article B │ ← You're reading
│ │
│ Article C │
└─────────────────────────┘Then, while you're reading, another user publishes a new article. Because the query is reactive, the new article is immediately inserted into the feed:
┌─────────────────────────┐
│ ✨ New Article │ ← Inserted
│ │
│ Article A │
│ │
│ Article B │ ← You were reading
│ │
│ Article C │
└─────────────────────────┘The application is doing exactly what it's supposed to do.
The data is correct.
The query is working correctly.
The UI is up to date.
But the user's context just changed underneath them.
They didn't ask for the feed to refresh. They didn't finish reading and decide to reload.
They were simply reading.
And that raises an interesting question:
Should receiving the latest data always mean showing the latest data immediately?
That's where the idea behind useBufferedState begins.
Reactivity Isn't Always the Same as Synchronization
Convex's reactive queries are extremely useful. They keep the UI in sync with changes happening on the server. For many parts of an application, that's exactly what we want.
A live dashboard, for example:
Database changes
↓
Convex query updates
↓
React receives new data
↓
UI updatesIn both cases, we usually want:
Latest server state = Latest UI state
When someone is reading, preserving their context can be more important than showing every update immediately. So instead of automatically synchronizing the UI, we can separate receiving an update from applying that update:
┌──────────┐
│ Database │
└────┬─────┘
│
↓
┌──────────────┐
│ Convex Query │
└────┬─────────┘
│
↓
┌─────────────────────┐
│ Latest data arrived │
└──────────┬──────────┘
│
├──────────────→ 🔔 Notify user
│
↓
┌───────────┐
│ Buffer │
└─────┬─────┘
│
│ User decides
↓
┌─────────┐
│ Sync │
└────┬────┘
↓
┌─────────┐
│ UI │
└─────────┘The query remains reactive.
What's different is when the UI chooses to apply the new state.
That distinction is the foundation of useBufferedState.
The Idea Behind useBufferedState
The solution I came up with was to separate the data coming from the server from the data currently being displayed.
Instead of treating the query result as the UI state, I keep two values:
upstream
↓
Latest data from Convex
currentVal
↓
Data currently being shown to the userThese two values are allowed to be different.
For example:
currentVal:
[A, B, C]
upstream:
[NEW, A, B, C]Convex knows about the new article.
Our application knows about the new article.
But the user can continue reading A, B, or C without the UI suddenly moving.
When the user decides they want the latest content, we synchronize the two.
That's what useBufferedState does.
The Hook
Here's the complete hook:
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
export function useBufferedState<T, D>(
upstream: T | null,
differ: (oldVal: T | null, newVal: T) => D,
) {
const [currentVal, setCurrentVal] = useState<T | null>(upstream);
const upstreamRef = useRef(upstream);
const hasLoadedInitialValue = useRef(upstream !== null);
upstreamRef.current = upstream;
useEffect(() => {
if (!hasLoadedInitialValue.current && upstream !== null) {
hasLoadedInitialValue.current = true;
setCurrentVal(upstream);
}
}, [upstream]);
const sync = useCallback(() => {
setCurrentVal(upstreamRef.current);
}, []);
const diff = useMemo(() => {
return upstream ? differ(currentVal, upstream) : null;
}, [currentVal, differ, upstream]);
return {
currentVal,
diff,
sync,
};
}It's a fairly small hook, but there are a few important ideas inside it.
Let's break it down.
Keeping the UI State Separate
The first thing we do is create local state:
const [currentVal, setCurrentVal] = useState<T | null>(upstream);This is the value that the UI will actually use.
Initially, we want the UI to show the data that came from the query.
So if Convex gives us:
[A, B, C]then our current value becomes:
currentVal = [A, B, C]Now suppose another user publishes something.
Convex gives us:
[NEW, A, B, C]The important thing is that we don't call setCurrentVal just because upstream changed.
So we end up with:
upstream = [NEW, A, B, C]
currentVal = [A, B, C]This is the entire idea behind the buffer.
The server has moved forward.
The UI hasn't.
Keeping Track of the Latest Data
We also keep a reference to the upstream value:
const upstreamRef = useRef(upstream);
upstreamRef.current = upstream;The ref always contains the latest value from Convex.
Why not just use upstream directly when we want to synchronize?
We could, but the ref gives the sync callback a stable way to access the latest upstream value without making sync depend on every query update.
Think of upstreamRef as our storage for:
"What is the latest data available right now?"
While currentVal answers:
"What data is the user currently looking at?"
Those are two different questions.
And that's exactly what we want.
Handling the Initial Load
There is another small problem we need to handle.
A Convex query can initially be null while it's loading.
So when the hook is first created, we might have:
upstream = nulland then later:
upstream = [A, B, C]We obviously want the first real value to become our initial UI state.
That's why the hook keeps track of whether we've received the initial value:
const hasLoadedInitialValue = useRef(upstream !== null);Then:
useEffect(() => {
if (!hasLoadedInitialValue.current && upstream !== null) {
hasLoadedInitialValue.current = true;
setCurrentVal(upstream);
}
}, [upstream]);This gives us a simple rule:
Use the first available upstream value to initialize the UI, but don't automatically replace the UI on every update after that.
The sync() Function
This is probably the most important part of the hook:
const sync = useCallback(() => {
setCurrentVal(upstreamRef.current);
}, []);Remember that upstreamRef.current always contains the latest data.
So calling:
sync();means:
"Okay, show me the latest data."
For our reading application, we could have a small indicator at the top of the feed:
┌──────────────────────────────────┐
│ ↑ 3 new articles available │
│ │
│ [Show new articles] │
└──────────────────────────────────┘The user can continue reading.
When they're ready, they click the button.
We call:
sync();And now:
Before:
currentVal = [A, B, C]
upstream = [NEW, A, B, C]
After sync():
currentVal = [NEW, A, B, C]
upstream = [NEW, A, B, C]The UI is now synchronized with the latest server state.
But How Do We Know There Are New Posts?
This is where the differ function comes in.
The hook accepts:
differ: (oldVal: T | null, newVal: T) => DAnd calculates:
const diff = useMemo(() => {
return upstream ? differ(currentVal, upstream) : null;
}, [currentVal, differ, upstream]);I intentionally made the hook unaware of what a "difference" actually means.
For a list of articles, maybe the difference is:
3 new articlesFor another application, it could mean:
2 records changedOr:
The current document has been modifiedOr even:
There is a conflictThe hook doesn't need to know.
The consumer decides what the difference means.
For example:
const { currentVal, diff, sync } = useBufferedState(
posts,
(current, latest) => {
if (!current) return latest.length;
return latest.length - current.length;
},
);Now we can use diff in the UI.
Something like:
{diff > 0 && (
<button onClick={sync}>
{diff} new articles available
</button>
)}So instead of automatically changing the feed, the application can tell the user:
"There is new content."
And then let the user decide what happens next.
Using It With Convex
The final component can be quite simple:
function Home() {
const posts = useQuery(api.posts.list);
const { currentVal, diff, sync } = useBufferedState(
posts,
(current, latest) => {
if (!current) return latest.length;
return latest.length - current.length;
},
);
return (
<div>
{diff > 0 && (
<button onClick={sync}>
{diff} new articles available
</button>
)}
{currentVal?.map((post) => (
<PostCard
key={post._id}
post={post}
/>
))}
</div>
);
}The important thing here is that we're still using:
useQuery(api.posts.list)The query remains reactive.
We're not disabling Convex reactivity.
We're simply putting a layer between the reactive data and the UI.
The data flow becomes:
Convex
│
│
reactive query
│
↓
upstream
│
┌──────┴──────┐
│ │
↓ ↓
latest value diff
│
│
↓
upstreamRef
│
│
wait for user
│
↓
sync()
│
↓
currentVal
│
↓
UIWhy Not Just Stop Using a Reactive Query?
This was an important question for me.
If reactivity is causing the problem, why not just fetch the data once and stop using a reactive query?
That would solve the UI problem, but we'd also lose one of the biggest benefits of Convex.
The application would no longer know when the underlying data changes.
I'd rather keep the reactivity and make the UI synchronization intentional.
That's the key difference.
I still want to know that new data exists.
I just don't necessarily want to force that data into the user's current context.
Where This Pattern Is Useful
The reading feed is just one example.
The same idea can be useful anywhere the user is interacting with a piece of data while that data can also change externally.
For example:
Reading feeds
A user is reading an article while new articles are published.
Don't move the feed underneath them.
Collaborative editors
Someone else changes a document while you're editing it.
You probably don't want their changes to blindly replace your current state.
Forms
A server-side record changes while a user is filling out a form.
Automatically replacing the form could destroy what they have typed.
Dashboards
A dashboard can continue receiving new data while the user is inspecting the current state.
The user can choose when to refresh the view.
Lists with frequent updates
If new items are constantly being added to a list, automatically inserting them at the top can cause the user's scroll position to jump.
A "Show new items" action can be much more pleasant.
The Bigger Idea
The interesting part of this problem isn't really the hook.
It's the distinction between data state and UI state.
A reactive backend tells us:
"This is the latest state of the world."
But the UI sometimes needs to answer a different question:
"What should the user see right now?"
Those two things don't always have to be identical.
In a real-time application, we can have:
Server state
↓
Latest available information
↓
Application decides when to apply it
↓
UI stateInstead of:
Server state
↓
Immediately replace UIThat small layer of control can make a big difference to the user experience.
Final Thoughts
I really like reactive systems because they remove a lot of unnecessary synchronization work.
But this experience reminded me that more real-time isn't always better UX.
Sometimes the best experience is not showing the latest information immediately.
Sometimes it's simply letting the user know:
"Hey, something changed. I'll leave your current view alone, and you can decide when you're ready to see it."
That's what useBufferedState is trying to provide.
It doesn't make Convex less reactive.
It doesn't fight against useQuery.
It simply separates receiving new data from deciding when that data should change the user's current view.
And in applications where preserving user context matters, that small distinction can be surprisingly valuable.
Further reading
Managing Reactivity with
useBufferedState— the Convex article/video that inspired this approach. Read on ConvexConvex React Documentation — learn how
useQuery,useMutation, and other React integrations work. Convex React DocsConvex
useQueryAPI — the reference for reactive queries and their behavior. useQuery API ReferenceConvex Overview — a good introduction to Convex's reactive database model. Convex Overview
