Skip to content

Commit 8643fad

Browse files
committed
feat: implement batch rendering
1 parent c81e309 commit 8643fad

25 files changed

+225
-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
@@ -7,7 +7,13 @@ export {
77
} from './queryCache'
88
export { setFocusHandler } from './setFocusHandler'
99
export { setOnlineHandler } from './setOnlineHandler'
10-
export { CancelledError, isCancelledError, isError, setConsole } from './utils'
10+
export {
11+
CancelledError,
12+
isCancelledError,
13+
isError,
14+
setConsole,
15+
setBatchedUpdates,
16+
} from './utils'
1117

1218
// Types
1319
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
@@ -352,9 +358,11 @@ export function makeQueryCache(config?: QueryCacheConfig) {
352358

353359
export function onVisibilityOrOnlineChange(type: 'focus' | 'online') {
354360
if (isDocumentVisible() && isOnline()) {
355-
queryCaches.forEach(queryCache => {
356-
queryCache.getQueries().forEach(query => {
357-
query.onInteraction(type)
361+
notifyManager.batch(() => {
362+
queryCaches.forEach(queryCache => {
363+
queryCache.getQueries().forEach(query => {
364+
query.onInteraction(type)
365+
})
358366
})
359367
})
360368
}

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

@@ -142,8 +143,13 @@ export class QueryObserver<TResult, TError> {
142143
}
143144
}
144145

145-
private notify(): void {
146-
this.listener?.(this.currentResult)
146+
private notify(global?: boolean): void {
147+
notifyManager.schedule(() => {
148+
this.listener?.(this.currentResult)
149+
if (global) {
150+
this.config.queryCache.notifyGlobalListeners(this.currentQuery)
151+
}
152+
})
147153
}
148154

149155
private updateStaleTimeout(): void {
@@ -165,8 +171,7 @@ export class QueryObserver<TResult, TError> {
165171
if (!this.isStale) {
166172
this.isStale = true
167173
this.updateResult()
168-
this.notify()
169-
this.config.queryCache.notifyGlobalListeners(this.currentQuery)
174+
this.notify(true)
170175
}
171176
}, timeout)
172177
}
@@ -214,20 +219,19 @@ export class QueryObserver<TResult, TError> {
214219
}
215220

216221
private updateResult(): void {
217-
const { currentQuery, previousQueryResult, config } = this
218-
const { state } = currentQuery
222+
const { state } = this.currentQuery
219223
let { data, status, updatedAt } = state
220224
let isPreviousData = false
221225

222226
// Keep previous data if needed
223227
if (
224-
config.keepPreviousData &&
228+
this.config.keepPreviousData &&
225229
state.isInitialData &&
226-
previousQueryResult?.isSuccess
230+
this.previousQueryResult?.isSuccess
227231
) {
228-
data = previousQueryResult.data
229-
updatedAt = previousQueryResult.updatedAt
230-
status = previousQueryResult.status
232+
data = this.previousQueryResult.data
233+
updatedAt = this.previousQueryResult.updatedAt
234+
status = this.previousQueryResult.status
231235
isPreviousData = true
232236
}
233237

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 { queryCache as defaultQueryCache, QueryCache } from '..'
8+
import { QueryCache, 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 = new QueryCache()
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)