Skip to content

Commit f12f3e8

Browse files
committed
feat: implement batch rendering
1 parent 460ab33 commit f12f3e8

25 files changed

+226
-115
lines changed

docs/src/pages/docs/comparison.md

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,26 +33,29 @@ Feature/Capability Key:
3333
| Scroll Recovery ||||
3434
| Cache Manipulation ||||
3535
| Outdated Query Dismissal ||||
36+
| Render Optimization<sup>2</sup> || 🛑 | 🛑 |
3637
| Auto Garbage Collection || 🛑 | 🛑 |
3738
| Mutation Hooks || 🟡 ||
3839
| Prefetching APIs || 🔶 ||
3940
| Query Cancellation || 🛑 | 🛑 |
40-
| Partial Query Matching<sup>2</sup> || 🛑 | 🛑 |
41+
| Partial Query Matching<sup>3</sup> || 🛑 | 🛑 |
4142
| Stale While Revalidate ||| 🛑 |
4243
| Stale Time Configuration || 🛑 | 🛑 |
4344
| Window Focus Refetching ||| 🛑 |
4445
| Network Status Refetching ||||
45-
| Automatic Refetch after Mutation<sup>3</sup> | 🔶 | 🔶 ||
46+
| Automatic Refetch after Mutation<sup>4</sup> | 🔶 | 🔶 ||
4647
| Cache Dehydration/Rehydration || 🛑 ||
4748
| React Suspense (Experimental) ||| 🛑 |
4849

4950
### Notes
5051

5152
> **<sup>1</sup> Lagged / "Lazy" Queries** - React Query provides a way to continue to see an existing query's data while the next query loads (similar to the same UX that suspense will soon provide natively). This is extremely important when writing pagination UIs or infinite loading UIs where you do not want to show a hard loading state whenever a new query is requested. Other libraries do not have this capability and render a hard loading state for the new query (unless it has been prefetched), while the new query loads.
5253
53-
> **<sup>2</sup> Partial query matching** - Because React Query uses deterministic query key serialization, this allows you to manipulate variable groups of queries without having to know each individual query-key that you want to match, eg. you can refetch every query that starts with `todos` in its key, regardless of variables, or you can target specific queries with (or without) variables or nested properties, and even use a filter function to only match queries that pass your specific conditions.
54+
> **<sup>2</sup> Render Optimization** - React Query has excellent rendering performance. It will only re-render your components when a query is updated. For example because it has new data, or to indicate it is fetching. React Query also batches updates together to make sure your application only re-renders once when multiple components are using the same query. If you are only interested in the `data` or `error` properties, you can reduce the number of renders even more by setting `notifyOnStatusChange` to `false`.
5455
55-
> **<sup>3</sup> Automatic Refetch after Mutation** - For truly automatic refetching to happen after a mutation occurs, a schema is necessary (like the one graphQL provides) along with heuristics that help the library know how to identify individual entities and entities types in that schema.
56+
> **<sup>3</sup> Partial query matching** - Because React Query uses deterministic query key serialization, this allows you to manipulate variable groups of queries without having to know each individual query-key that you want to match, eg. you can refetch every query that starts with `todos` in its key, regardless of variables, or you can target specific queries with (or without) variables or nested properties, and even use a filter function to only match queries that pass your specific conditions.
57+
58+
> **<sup>4</sup> Automatic Refetch after Mutation** - For truly automatic refetching to happen after a mutation occurs, a schema is necessary (like the one graphQL provides) along with heuristics that help the library know how to identify individual entities and entities types in that schema.
5659
5760
[swr]: https://github.com/vercel/swr
5861
[apollo]: https://github.com/apollographql/apollo-client

rollup.config.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,12 @@ import commonJS from 'rollup-plugin-commonjs'
77
import visualizer from 'rollup-plugin-visualizer'
88
import replace from '@rollup/plugin-replace'
99

10-
const external = ['react']
10+
const external = ['react', 'react-dom']
1111
const hydrationExternal = [...external, 'react-query']
1212

1313
const globals = {
1414
react: 'React',
15+
'react-dom': 'ReactDOM',
1516
}
1617
const hydrationGlobals = {
1718
...globals,

src/core/index.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,13 @@ export { getDefaultReactQueryConfig } from './config'
22
export { queryCache, queryCaches, makeQueryCache } from './queryCache'
33
export { setFocusHandler } from './setFocusHandler'
44
export { setOnlineHandler } from './setOnlineHandler'
5-
export { CancelledError, isCancelledError, isError, setConsole } from './utils'
5+
export {
6+
CancelledError,
7+
isCancelledError,
8+
isError,
9+
setConsole,
10+
setBatchedUpdates,
11+
} from './utils'
612

713
// Types
814
export * from './types'

src/core/notifyManager.ts

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import { getBatchedUpdates, scheduleMicrotask } from './utils'
2+
3+
// TYPES
4+
5+
type NotifyCallback = () => void
6+
7+
// CLASS
8+
9+
export class NotifyManager {
10+
private queue: NotifyCallback[]
11+
private transactions: number
12+
13+
constructor() {
14+
this.queue = []
15+
this.transactions = 0
16+
}
17+
18+
batch(callback: () => void): void {
19+
this.transactions++
20+
callback()
21+
this.transactions--
22+
if (!this.transactions) {
23+
this.flush()
24+
}
25+
}
26+
27+
schedule(notify: NotifyCallback): void {
28+
if (this.transactions) {
29+
this.queue.push(notify)
30+
} else {
31+
scheduleMicrotask(() => {
32+
notify()
33+
})
34+
}
35+
}
36+
37+
flush(): void {
38+
const queue = this.queue
39+
this.queue = []
40+
if (queue.length) {
41+
scheduleMicrotask(() => {
42+
const batchedUpdates = getBatchedUpdates()
43+
batchedUpdates(() => {
44+
queue.forEach(notify => {
45+
notify()
46+
})
47+
})
48+
})
49+
}
50+
}
51+
}
52+
53+
// SINGLETON
54+
55+
export const notifyManager = new NotifyManager()

src/core/query.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import {
2323
} from './types'
2424
import type { QueryCache } from './queryCache'
2525
import { QueryObserver, UpdateListener } from './queryObserver'
26+
import { notifyManager } from './notifyManager'
2627

2728
// TYPES
2829

@@ -127,11 +128,13 @@ export class Query<TResult, TError> {
127128
private dispatch(action: Action<TResult, TError>): void {
128129
this.state = queryReducer(this.state, action)
129130

130-
this.observers.forEach(observer => {
131-
observer.onQueryUpdate(action)
132-
})
131+
notifyManager.batch(() => {
132+
this.observers.forEach(observer => {
133+
observer.onQueryUpdate(action)
134+
})
133135

134-
this.queryCache.notifyGlobalListeners(this)
136+
this.queryCache.notifyGlobalListeners(this)
137+
})
135138
}
136139

137140
private scheduleGc(): void {

src/core/queryCache.ts

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ import {
33
deepIncludes,
44
getQueryArgs,
55
isDocumentVisible,
6-
isPlainObject,
76
isOnline,
7+
isPlainObject,
88
isServer,
99
} from './utils'
1010
import { getResolvedQueryConfig } from './config'
@@ -18,6 +18,7 @@ import {
1818
TypedQueryFunctionArgs,
1919
ResolvedQueryConfig,
2020
} from './types'
21+
import { notifyManager } from './notifyManager'
2122

2223
// TYPES
2324

@@ -89,8 +90,12 @@ export class QueryCache {
8990
0
9091
)
9192

92-
this.globalListeners.forEach(listener => {
93-
listener(this, query)
93+
notifyManager.batch(() => {
94+
this.globalListeners.forEach(listener => {
95+
notifyManager.schedule(() => {
96+
listener(this, query)
97+
})
98+
})
9499
})
95100
}
96101

@@ -194,17 +199,18 @@ export class QueryCache {
194199
options || {}
195200

196201
try {
197-
await Promise.all(
198-
this.getQueries(predicate, options).map(query => {
199-
const enabled = query.isEnabled()
202+
const promises: Promise<unknown>[] = []
200203

204+
notifyManager.batch(() => {
205+
this.getQueries(predicate, options).forEach(query => {
206+
const enabled = query.isEnabled()
201207
if ((enabled && refetchActive) || (!enabled && refetchInactive)) {
202-
return query.fetch()
208+
promises.push(query.fetch())
203209
}
204-
205-
return undefined
206210
})
207-
)
211+
})
212+
213+
await Promise.all(promises)
208214
} catch (err) {
209215
if (throwOnError) {
210216
throw err
@@ -349,9 +355,11 @@ export function makeQueryCache(config?: QueryCacheConfig) {
349355

350356
export function onVisibilityOrOnlineChange(type: 'focus' | 'online') {
351357
if (isDocumentVisible() && isOnline()) {
352-
queryCaches.forEach(queryCache => {
353-
queryCache.getQueries().forEach(query => {
354-
query.onInteraction(type)
358+
notifyManager.batch(() => {
359+
queryCaches.forEach(queryCache => {
360+
queryCache.getQueries().forEach(query => {
361+
query.onInteraction(type)
362+
})
355363
})
356364
})
357365
}

src/core/queryObserver.ts

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
isValidTimeout,
66
noop,
77
} from './utils'
8+
import { notifyManager } from './notifyManager'
89
import type { QueryResult, ResolvedQueryConfig } from './types'
910
import type { Query, Action, FetchMoreOptions, RefetchOptions } from './query'
1011

@@ -139,8 +140,13 @@ export class QueryObserver<TResult, TError> {
139140
}
140141
}
141142

142-
private notify(): void {
143-
this.listener?.(this.currentResult)
143+
private notify(global?: boolean): void {
144+
notifyManager.schedule(() => {
145+
this.listener?.(this.currentResult)
146+
if (global) {
147+
this.config.queryCache.notifyGlobalListeners(this.currentQuery)
148+
}
149+
})
144150
}
145151

146152
private updateStaleTimeout(): void {
@@ -162,8 +168,7 @@ export class QueryObserver<TResult, TError> {
162168
if (!this.isStale) {
163169
this.isStale = true
164170
this.updateResult()
165-
this.notify()
166-
this.config.queryCache.notifyGlobalListeners(this.currentQuery)
171+
this.notify(true)
167172
}
168173
}, timeout)
169174
}
@@ -211,20 +216,19 @@ export class QueryObserver<TResult, TError> {
211216
}
212217

213218
private updateResult(): void {
214-
const { currentQuery, previousQueryResult, config } = this
215-
const { state } = currentQuery
219+
const { state } = this.currentQuery
216220
let { data, status, updatedAt } = state
217221
let isPreviousData = false
218222

219223
// Keep previous data if needed
220224
if (
221-
config.keepPreviousData &&
225+
this.config.keepPreviousData &&
222226
state.isInitialData &&
223-
previousQueryResult?.isSuccess
227+
this.previousQueryResult?.isSuccess
224228
) {
225-
data = previousQueryResult.data
226-
updatedAt = previousQueryResult.updatedAt
227-
status = previousQueryResult.status
229+
data = this.previousQueryResult.data
230+
updatedAt = this.previousQueryResult.updatedAt
231+
status = this.previousQueryResult.status
228232
isPreviousData = true
229233
}
230234

src/core/tests/queryCache.test.tsx

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
mockConsoleError,
66
mockNavigatorOnLine,
77
} from '../../react/tests/utils'
8-
import { makeQueryCache, queryCache as defaultQueryCache } from '..'
8+
import { makeQueryCache, queryCache as defaultQueryCache } from '../..'
99
import { isCancelledError, isError } from '../utils'
1010

1111
describe('queryCache', () => {
@@ -348,14 +348,15 @@ describe('queryCache', () => {
348348
expect(query.queryCache).toBe(queryCache)
349349
})
350350

351-
test('notifyGlobalListeners passes the same instance', () => {
351+
test('notifyGlobalListeners passes the same instance', async () => {
352352
const key = queryKey()
353353

354354
const queryCache = makeQueryCache()
355355
const subscriber = jest.fn()
356356
const unsubscribe = queryCache.subscribe(subscriber)
357357
const query = queryCache.buildQuery(key)
358358
query.setData('foo')
359+
await sleep(1)
359360
expect(subscriber).toHaveBeenCalledWith(queryCache, query)
360361

361362
unsubscribe()

src/core/tests/utils.test.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { replaceEqualDeep, deepIncludes, isPlainObject } from '../utils'
2-
import { setConsole, queryCache } from '..'
2+
import { setConsole, queryCache } from '../..'
33
import { queryKey } from '../../react/tests/utils'
44

55
describe('core/utils', () => {

src/core/utils.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,3 +250,34 @@ export function createSetHandler(fn: () => void) {
250250
removePreviousHandler = callback(fn)
251251
}
252252
}
253+
254+
/**
255+
* Schedules a microtask.
256+
* This can be useful to schedule state updates after rendering.
257+
*/
258+
export function scheduleMicrotask(callback: () => void): void {
259+
Promise.resolve()
260+
.then(callback)
261+
.catch(error =>
262+
setTimeout(() => {
263+
throw error
264+
})
265+
)
266+
}
267+
268+
type BatchUpdateFunction = (callback: () => void) => void
269+
270+
// Default to a dummy "batch" implementation that just runs the callback
271+
let batchedUpdates: BatchUpdateFunction = (callback: () => void) => {
272+
callback()
273+
}
274+
275+
// Allow injecting another batching function later
276+
export function setBatchedUpdates(fn: BatchUpdateFunction) {
277+
batchedUpdates = fn
278+
}
279+
280+
// Supply a getter just to skip dealing with ESM bindings
281+
export function getBatchedUpdates(): BatchUpdateFunction {
282+
return batchedUpdates
283+
}

0 commit comments

Comments
 (0)