Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/query-cache-equality.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@tanstack/query-core': major
---

Add optional `equalityFn` and `hashFn` configuration to `QueryCache.queryKey` and `MutationCache.mutationKey` for custom key comparison and hashing. Extend `replaceEqualDeep` with an optional equality function for structural sharing of custom value types. Remove the per-query `queryKeyHashFn` option and the `QueryKeyHashFunction` type. Configure `new QueryCache({ queryKey: { hashFn } })` on the client to customize hashing. To apply different hashes to different queries, branch on the key inside `hashFn` and use `hashKey` for the default.

Partial key matching now recurses only into plain arrays and objects. Use `equalityFn` to compare values such as `Date` instances. The third argument to `replaceEqualDeep` now accepts an equality function. The recursion depth is managed internally.
17 changes: 17 additions & 0 deletions docs/framework/react/guides/render-optimizations.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,23 @@ React Query uses a technique called "structural sharing" to ensure that as many

> Note: This optimization only works if the `queryFn` returns JSON compatible data. You can turn it off by setting `structuralSharing: false` globally or on a per-query basis, or you can implement your own structural sharing by passing a function to it.

If your data contains custom value types, you can pass an equality function to `replaceEqualDeep` from your `structuralSharing` function. The previous value is kept when the function returns `true`:

```tsx
import { replaceEqualDeep, useQuery } from '@tanstack/react-query'

const equalityFn = (a: unknown, b: unknown) =>
a === b ||
(a instanceof Date && b instanceof Date && a.getTime() === b.getTime())

useQuery({
queryKey: ['events'],
queryFn: fetchEvents,
structuralSharing: (oldData, newData) =>
replaceEqualDeep(oldData, newData, equalityFn),
})
```

### referential identity

The top level object returned from `useQuery`, `useInfiniteQuery`, `useMutation` and the Array returned from `useQueries` is **not referentially stable**. It will be a new reference on every render. However, the `data` properties returned from these hooks will be as stable as possible.
Expand Down
22 changes: 15 additions & 7 deletions packages/preact-query/src/__tests__/useQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4905,17 +4905,21 @@ describe('useQuery', () => {
let hashes = 0
let renders = 0

function queryKeyHashFn(x: any) {
function hashFn(queryKey: ReadonlyArray<unknown>) {
hashes++
return JSON.stringify(x)
return JSON.stringify(queryKey)
}

queryClient = new QueryClient({
queryCache: new QueryCache({ queryKey: { hashFn } }),
})

function Page() {
useEffect(() => {
renders++
})

useQuery({ queryKey: key, queryFn: () => 'test', queryKeyHashFn })
useQuery({ queryKey: key, queryFn: () => 'test' })
return null
}

Expand All @@ -4928,23 +4932,27 @@ describe('useQuery', () => {
it('should hash query keys that contain bigints given a supported query hash function', async () => {
const key = [createKey(), 1n]

function queryKeyHashFn(x: any) {
return JSON.stringify(x, (_, value) => {
function hashFn(queryKey: ReadonlyArray<unknown>) {
return JSON.stringify(queryKey, (_, value) => {
if (typeof value === 'bigint') return value.toString()
return value
})
}

queryClient = new QueryClient({
queryCache: new QueryCache({ queryKey: { hashFn } }),
})

function Page() {
useQuery({ queryKey: key, queryFn: () => 'test', queryKeyHashFn })
useQuery({ queryKey: key, queryFn: () => 'test' })
return null
}

renderWithClient(queryClient, <Page />)

await vi.advanceTimersByTimeAsync(0)

const query = queryClient.getQueryCache().get(queryKeyHashFn(key))
const query = queryClient.getQueryCache().get(hashFn(key))
expect(query?.state.data).toBe('test')
})

Expand Down
4 changes: 2 additions & 2 deletions packages/query-core/src/__tests__/mutationCache.test-d.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,9 @@ describe('mutationCache', () => {
})

describe('MutationCacheConfig', () => {
it('should declare exactly its four callbacks', () => {
it('should declare its key configuration and four callbacks', () => {
expectTypeOf<keyof MutationCacheConfig>().toEqualTypeOf<
'onError' | 'onSuccess' | 'onMutate' | 'onSettled'
'mutationKey' | 'onError' | 'onSuccess' | 'onMutate' | 'onSettled'
>()
})

Expand Down
43 changes: 43 additions & 0 deletions packages/query-core/src/__tests__/mutationCache.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,49 @@ describe('mutationCache', () => {
}),
).toStrictEqual(mutation)
})

it('should use the MutationCache equality function for partial mutation key matching', () => {
const equalityFn = (a: unknown, b: unknown) =>
typeof a === 'string' && typeof b === 'string'
? a.toLowerCase() === b.toLowerCase()
: a === b
const testCache = new MutationCache({ mutationKey: { equalityFn } })
const testClient = new QueryClient({ mutationCache: testCache })
const mutation = Mutation.build(testClient, {
mutationKey: ['todos', { status: 'done' }],
mutationFn: () => Promise.resolve(),
})

expect(
testCache.find({
mutationKey: ['TODOS', { status: 'DONE' }],
exact: false,
}),
).toBe(mutation)
expect(
testCache.findAll({
mutationKey: ['TODOS', { status: 'DONE' }],
}),
).toStrictEqual([mutation])

testClient.clear()
})

it('should use the MutationCache mutation key hash function for exact matching', () => {
const key = ['todos', { status: 'done' }]
const hashFn = vi.fn<() => string>(() => 'custom-hash')
const testCache = new MutationCache({ mutationKey: { hashFn } })
const testClient = new QueryClient({ mutationCache: testCache })
const mutation = Mutation.build(testClient, {
mutationKey: key,
mutationFn: () => Promise.resolve(),
})

expect(testCache.find({ mutationKey: [...key] })).toBe(mutation)
expect(hashFn).toHaveBeenCalledWith(key)

testClient.clear()
})
})

describe('findAll', () => {
Expand Down
17 changes: 13 additions & 4 deletions packages/query-core/src/__tests__/query.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
hydrate,
noop,
} from '..'
import { hashQueryKeyByOptions } from '../utils'
import { hashKeyByOptions } from '../utils'
import { mockOnlineManagerIsOnline, setIsServer } from './utils'
import type {
QueryCacheNotifyEvent,
Expand Down Expand Up @@ -1359,7 +1359,10 @@ describe('query', () => {
const query = new Query({
client: queryClient,
queryKey: key,
queryHash: hashQueryKeyByOptions(key),
queryHash: hashKeyByOptions(
key,
queryClient.getQueryCache().config.queryKey,
),
})

query.addObserver(observer)
Expand Down Expand Up @@ -1392,7 +1395,10 @@ describe('query', () => {
const query = new Query({
client: queryClient,
queryKey: key,
queryHash: hashQueryKeyByOptions(key),
queryHash: hashKeyByOptions(
key,
queryClient.getQueryCache().config.queryKey,
),
options: {
queryFn: () => 'data',
initialData: initialDataFn,
Expand Down Expand Up @@ -1475,7 +1481,10 @@ describe('query', () => {
const query = new Query({
client: queryClient,
queryKey: key,
queryHash: hashQueryKeyByOptions(key),
queryHash: hashKeyByOptions(
key,
queryClient.getQueryCache().config.queryKey,
),
options: { queryFn },
})

Expand Down
4 changes: 3 additions & 1 deletion packages/query-core/src/__tests__/queryCache.test-d.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createKey } from '@tanstack/query-test-utils'
import { afterEach, beforeEach, describe, expectTypeOf, it } from 'vitest'
import { QueryCache, QueryClient } from '..'
import type {
CacheKeyConfig,
DefaultError,
NotifyEvent,
NotifyEventType,
Expand Down Expand Up @@ -77,8 +78,9 @@ describe('queryCache', () => {
})

describe('QueryCacheConfig', () => {
it('should declare every callback as optional', () => {
it('should declare every option as optional', () => {
expectTypeOf<QueryCacheConfig>().toEqualTypeOf<{
queryKey?: CacheKeyConfig<QueryKey>
onError?: (
error: DefaultError,
query: Query<unknown, unknown, unknown>,
Expand Down
90 changes: 90 additions & 0 deletions packages/query-core/src/__tests__/queryCache.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,30 @@ describe('queryCache', () => {
const query = queryCache.find({ queryKey: key, exact: false })!
expect(query.state.data).toBe('data1')
})

it('should use the QueryCache equality function for partial query key matching', () => {
const equalityFn = (a: unknown, b: unknown) =>
typeof a === 'string' && typeof b === 'string'
? a.toLowerCase() === b.toLowerCase()
: a === b
const testCache = new QueryCache({ queryKey: { equalityFn } })
const testClient = new QueryClient({ queryCache: testCache })
const query = testClient.getQueryCache().build(testClient, {
queryKey: ['todos', { status: 'done' }],
})

expect(
testCache.find({
queryKey: ['TODOS', { status: 'DONE' }],
exact: false,
}),
).toBe(query)
expect(
testCache.findAll({ queryKey: ['TODOS', { status: 'DONE' }] }),
).toStrictEqual([query])

testClient.clear()
})
})

describe('findAll', () => {
Expand Down Expand Up @@ -363,6 +387,59 @@ describe('queryCache', () => {
.catch(noop)
expect(queryCache.findAll()).toHaveLength(2)
})

it('should return all the queries when key contains object with an undefined property (#3741)', async () => {
const baseKey = createKey()

const client = new QueryClient({
queryCache: new QueryCache({
queryKey: {
equalityFn: (a, b) => b === undefined || Object.is(a, b),
},
}),
})

const keyForId = (id?: number) => [{ ...baseKey, a: id }]

await client.query({ queryKey: keyForId(1), queryFn: () => 'data1' })
await client.query({
queryKey: keyForId(),
queryFn: () => 'data-nothing',
})
expect(
client.getQueryCache().findAll({ queryKey: keyForId() }),
).toHaveLength(2)
})

it('should invalidate matching dates (#10982)', async () => {
const client = new QueryClient({
queryCache: new QueryCache({
queryKey: {
equalityFn: (a, b) => {
if (a instanceof Date && b instanceof Date) {
return a.toISOString() === b.toISOString()
}
return a === b
},
},
}),
})

await client.query({
queryKey: ['report', { from: new Date('2020-01-01') }],
queryFn: () => 'data1',
})
await client.query({
queryKey: ['report', { from: new Date('2021-06-25') }],
queryFn: () => 'data2',
})

expect(
client.getQueryCache().findAll({
queryKey: ['report', { from: new Date('2020-01-01') }],
}),
).toHaveLength(1)
})
})

describe('QueryCacheConfig error callbacks', () => {
Expand Down Expand Up @@ -451,6 +528,19 @@ describe('queryCache', () => {
expect(query.queryHash).toBe(hashKey(key))
})

it('should use the QueryCache query key hash function', () => {
const key = createKey()
const hashFn = vi.fn<() => string>(() => 'custom-hash')
const testCache = new QueryCache({ queryKey: { hashFn } })
const testClient = new QueryClient({ queryCache: testCache })

const query = testCache.build(testClient, { queryKey: key })

expect(query.queryHash).toBe('custom-hash')
expect(testCache.find({ queryKey: key })).toBe(query)
expect(hashFn).toHaveBeenCalledWith(key)
})

it('should use provided queryHash instead of computing it', () => {
const key = createKey()
const customHash = 'custom-hash'
Expand Down
Loading
Loading