TL;DR
- By default, React Query keeps polling while the page is
visible. A Tauri window staysvisiblewhen it loses focus or sits behind other windows. focusManager.setEventListenernow also listens to Tauri’sonFocusChanged, so polling stops while the window is unfocused.- A hook spread the whole query result, so every reader re-rendered when each fetch started and ended. It now returns only the values it needs and sets
notifyOnChangeProps. - While an answer streams in, finished blocks are memoized and only the last, unfinished block is parsed again.
A Tauri desktop app that shows conversations with agents spiked its CPU usage every few seconds while doing nothing. Dozens of polling requests a minute went out with nobody looking. While an answer streamed in, it got heavier still. On macOS the WebView is WKWebView.
Polling does not stop in a window behind other windows
React Query’s refetchInterval stops while focusManager considers the app unfocused, as long as refetchIntervalInBackground is false (the default).
But the default focusManager only listens to visibilitychange. In a browser, switching tabs makes the page hidden. A Tauri window stays visible when it is behind another app or loses focus. The assumption “visible means someone is looking” does not hold on the desktop.
So I replaced the focus check with focusManager.setEventListener, which the library provides for this.
focusManager.setEventListener(setFocused => {
let windowFocused = document.hasFocus();
const update = () =>
setFocused(document.visibilityState === 'visible' && windowFocused);
const unlisten = getCurrentWindow().onFocusChanged(({ payload }) => {
windowFocused = payload;
update();
});
document.addEventListener('visibilitychange', update);
update();
return () => {
document.removeEventListener('visibilitychange', update);
void unlisten.then(off => off());
};
});
The app counts as focused only when it is visible and the window has focus. The initial value comes from document.hasFocus(), because the app’s permissions allow receiving Tauri events but not the command that asks for focus.
The real code adds two things:
- When focus moves into an iframe, the parent’s
blurarrives first. Once focus has settled in the iframe,document.hasFocus()returnstrue, so it is read aftersetTimeout(0). - If a focus event is missed, a click or key press inside the window marks it focused again.
Refetching only the paused queries when focus returns
When focus returns, queries that went stale while paused need to be fetched again. Turning on React Query’s refetchOnWindowFocus would do it, but it refetches every active query that is stale. In my app that includes heavy detail queries and infinite lists, which realtime updates already keep current.
So refetchOnWindowFocus stays off. When focus returns, refetchQueries fetches only the queries that poll and are stale.
Each poll re-rendered components that had nothing to do with it
With polling paused, fetches still run every 5 or 30 seconds while someone is looking. Even when the result did not change, every component that read the same query re-rendered twice.
The cause was a custom hook that spread the whole query result. React Query records which properties a component reads and re-renders only when one of them changes (tracked properties). A spread reads every property, including isFetching. isFetching changes when a fetch starts and when it ends, so each fetch caused two re-renders.
The hook now returns only what is used, and notifyOnChangeProps names only data and isFetched.
const query = useQuery({
queryKey: ['sessions', taskId],
queryFn: () => fetchSessions(taskId),
refetchInterval: current => (isSettled(current.state.data) ? 30_000 : 5_000),
notifyOnChangeProps: ['data', 'isFetched'],
});
return {
isFetched: query.isFetched,
sessions: query.data?.sessions ?? NO_SESSIONS,
};
NO_SESSIONS is an empty array defined at module level. Writing ?? [] creates a new array on every render while there is no data, which defeats memoization in the components that receive it.
The whole answer was parsed again while it streamed
Answers arrive a little at a time. Incoming events are applied in batches every 50 milliseconds.
Each batch rebuilt the layout of the whole thread. Now the previous layout is passed in, and unchanged parts reuse the same objects. The thread’s components are memoized, so the same reference means no re-render.
The other cost was Markdown. The answer’s Markdown was parsed from the start every 50 milliseconds. The longer the answer, the heavier each parse and the more parses there are.
In this stream, text that has arrived is never rewritten; it is only appended. So a finished block never changes again, and the answer can be split into blocks:
- Finished blocks are rendered by a memoized component and parsed once.
- Only the last block, still being written, is parsed on every batch.
The hard part is where to split. A wrong split shows one list or table as two. So the rule prefers splitting too little over splitting too much:
- Split only after a blank line outside a code block.
- If the next line is indented, a list item, a quote or a table row, treat it as a continuation and do not split.
- Never split at the last line, which is still being written. A
-there may be about to become a list item.
A missed split only makes a block larger. The output stays correct.