Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
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
2 changes: 1 addition & 1 deletion docs/src/pages/comparison.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ Feature/Capability Key:

> **<sup>1</sup> Lagged Query Data** - 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.

> **<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 `notifyOnChangeProps` to `['data', 'error']`.
> **<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 `notifyOnChangeProps` to `['data', 'error']`, or set `notifyOnChangeTracked: true` to automatically track which fields are accessed and only re-render if one of them changes.

> **<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.

Expand Down
6 changes: 5 additions & 1 deletion docs/src/pages/reference/useQuery.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const {
keepPreviousData,
notifyOnChangeProps,
notifyOnChangePropsExclusions,
notifyOnChangeTracked,
onError,
onSettled,
onSuccess,
Expand All @@ -39,7 +40,7 @@ const {
refetchOnWindowFocus,
retry,
retryDelay,
select
select,
staleTime,
structuralSharing,
suspense,
Expand Down Expand Up @@ -117,6 +118,9 @@ const result = useQuery({
- Optional
- If set, the component will not re-render if any of the listed properties change.
- If set to `['isStale']` for example, the component will not re-render when the `isStale` property changes.
- `notifyOnChangeTracked`
Comment thread
boschni marked this conversation as resolved.
Outdated
- Optional
- If set, access to properties will be tracked, and the component will only re-render when one of the tracked properties change.
- `onSuccess: (data: TData) => void`
- Optional
- This function will fire any time the query successfully fetches new data.
Expand Down
31 changes: 31 additions & 0 deletions src/core/queryObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,37 @@ export class QueryObserver<
this.currentQuery.removeObserver(this)
}

createQueryResult(
Comment thread
boschni marked this conversation as resolved.
Outdated
queryObserverResult: QueryObserverResult<TData, TError>
): QueryObserverResult<TData, TError> {
if (this.options.notifyOnChangeTracked) {
const trackedResult = {}
Comment thread
boschni marked this conversation as resolved.
Outdated
const addNotifyOnChangeProps = (prop: keyof QueryObserverResult) => {
if (!this.options.notifyOnChangeProps) {
this.options.notifyOnChangeProps = []
}

if (!this.options.notifyOnChangeProps.includes(prop)) {
this.options.notifyOnChangeProps.push(prop)
Comment thread
boschni marked this conversation as resolved.
Outdated
}
}

Object.keys(queryObserverResult).forEach(key => {
Object.defineProperty(trackedResult, key, {
configurable: false,
enumerable: true,
get() {
addNotifyOnChangeProps(key as keyof QueryObserverResult)
return queryObserverResult[key as keyof QueryObserverResult]
},
})
})

return trackedResult as QueryObserverResult<TData, TError>
}
return queryObserverResult
}

setOptions(
options?: QueryObserverOptions<TQueryFnData, TError, TData, TQueryData>
): void {
Expand Down
4 changes: 4 additions & 0 deletions src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,10 @@ export interface QueryObserverOptions<
* If set, the component will not re-render if any of the listed properties change.
*/
notifyOnChangePropsExclusions?: Array<keyof InfiniteQueryObserverResult>
/**
* If set, access to properties will be tracked, and the component will only re-render when one of the tracked properties change.
*/
notifyOnChangeTracked?: boolean
/**
* This callback will fire any time the query successfully fetches new data.
*/
Expand Down
35 changes: 35 additions & 0 deletions src/react/tests/useQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -737,6 +737,41 @@ describe('useQuery', () => {
expect(states[1].dataUpdatedAt).not.toBe(states[2].dataUpdatedAt)
})

it('should track properties and only re-render when a tracked property changes', async () => {
Comment thread
boschni marked this conversation as resolved.
const key = queryKey()
const states: UseQueryResult<string>[] = []

function Page() {
const state = useQuery(key, () => 'test', {
notifyOnChangeTracked: true,
})

states.push(state)

const { refetch, data } = state

React.useEffect(() => {
if (data) {
refetch()
}
}, [refetch, data])

return (
<div>
<h1>{data ?? null}</h1>
</div>
)
}

const rendered = renderWithClient(queryClient, <Page />)

await waitFor(() => rendered.getByText('test'))

expect(states.length).toBe(2)
expect(states[0]).toMatchObject({ data: undefined })
expect(states[1]).toMatchObject({ data: 'test' })
})

it('should be able to remove a query', async () => {
const key = queryKey()
const states: UseQueryResult<number>[] = []
Expand Down
2 changes: 1 addition & 1 deletion src/react/useBaseQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,5 +91,5 @@ export function useBaseQuery<TQueryFnData, TError, TData, TQueryData>(
}
}

return currentResult
return observer.createQueryResult(currentResult)
}