diff --git a/docs/src/pages/comparison.md b/docs/src/pages/comparison.md index 4a3691ed4c..dfa06c741d 100644 --- a/docs/src/pages/comparison.md +++ b/docs/src/pages/comparison.md @@ -64,7 +64,7 @@ Feature/Capability Key: > **1 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. -> **2 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']`. Set `notifyOnChangeProps: 'tracked'` to automatically track which fields are accessed and only re-render if one of them changes. +> **2 Render Optimization** - React Query has excellent rendering performance. By default, it will automatically track which fields are accessed and only re-render if one of them changes. If you would like to opt-out of this optimization, setting `notifyOnChangeProps` to `'all'` will re-render your components whenever the 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']`. > **3 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. diff --git a/docs/src/pages/guides/migrating-to-react-query-4.md b/docs/src/pages/guides/migrating-to-react-query-4.md index 44000c1e98..539813f1d4 100644 --- a/docs/src/pages/guides/migrating-to-react-query-4.md +++ b/docs/src/pages/guides/migrating-to-react-query-4.md @@ -27,6 +27,16 @@ With version [3.22.0](https://github.com/tannerlinsley/react-query/releases/tag/ + import { dehydrate, hydrate, useHydrate, Hydrate } from 'react-query' ``` +### `notifyOnChangeProps` property no longer accepts `"tracked"` as a value + +The `notifyOnChangeProps` option no longer accepts a `"tracked"` value. Instead, `useQuery` defaults to tracking properties. All queries using `notifyOnChangeProps: "tracked"` should be updated by removing this option. + +If you would like to bypass this in any queries to emulate the v3 default behavior of re-rendering whenever a query changes, `notifyOnChangeProps` now accepts an `"all"` value to opt-out of the default smart tracking optimization. + +### `notifyOnChangePropsExclusion` has been removed + +In v4, `notifyOnChangeProps` defaults to the `"tracked"` behavior of v3 instead of `undefined`. Now that `"tracked"` is the default behavior for v4, it no longer makes sense to include this config option. + ### Consistent behavior for `cancelRefetch` The `cancelRefetch` can be passed to all functions that imperatively fetch a query, namely: diff --git a/docs/src/pages/reference/QueryClient.md b/docs/src/pages/reference/QueryClient.md index 63140f8fae..b195e050d0 100644 --- a/docs/src/pages/reference/QueryClient.md +++ b/docs/src/pages/reference/QueryClient.md @@ -91,7 +91,7 @@ try { **Options** -The options for `fetchQuery` are exactly the same as those of [`useQuery`](./useQuery), except the following: `enabled, refetchInterval, refetchIntervalInBackground, refetchOnWindowFocus, refetchOnReconnect, notifyOnChangeProps, notifyOnChangePropsExclusions, onSuccess, onError, onSettled, useErrorBoundary, select, suspense, keepPreviousData, placeholderData`; which are strictly for useQuery and useInfiniteQuery. You can check the [source code](https://github.com/tannerlinsley/react-query/blob/361935a12cec6f36d0bd6ba12e84136c405047c5/src/core/types.ts#L83) for more clarity. +The options for `fetchQuery` are exactly the same as those of [`useQuery`](./useQuery), except the following: `enabled, refetchInterval, refetchIntervalInBackground, refetchOnWindowFocus, refetchOnReconnect, notifyOnChangeProps, onSuccess, onError, onSettled, useErrorBoundary, select, suspense, keepPreviousData, placeholderData`; which are strictly for useQuery and useInfiniteQuery. You can check the [source code](https://github.com/tannerlinsley/react-query/blob/361935a12cec6f36d0bd6ba12e84136c405047c5/src/core/types.ts#L83) for more clarity. **Returns** diff --git a/docs/src/pages/reference/useQuery.md b/docs/src/pages/reference/useQuery.md index b0017d893b..5afeee10ae 100644 --- a/docs/src/pages/reference/useQuery.md +++ b/docs/src/pages/reference/useQuery.md @@ -35,7 +35,6 @@ const { keepPreviousData, meta, notifyOnChangeProps, - notifyOnChangePropsExclusions, onError, onSettled, onSuccess, @@ -125,15 +124,12 @@ const result = useQuery({ - If set to `true`, the query will refetch on reconnect if the data is stale. - If set to `false`, the query will not refetch on reconnect. - If set to `"always"`, the query will always refetch on reconnect. -- `notifyOnChangeProps: string[] | "tracked"` +- `notifyOnChangeProps: string[] | "all"` - Optional - If set, the component will only re-render if any of the listed properties change. - If set to `['data', 'error']` for example, the component will only re-render when the `data` or `error` properties change. - - If set to `"tracked"`, access to properties will be tracked, and the component will only re-render when one of the tracked properties change. -- `notifyOnChangePropsExclusions: string[]` - - 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. + - If set to `"all"`, the component will opt-out of smart tracking and re-render whenever a query is updated. + - By default, 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. diff --git a/src/core/queryObserver.ts b/src/core/queryObserver.ts index 2ef23baffc..0cc8d3b8c1 100644 --- a/src/core/queryObserver.ts +++ b/src/core/queryObserver.ts @@ -610,27 +610,22 @@ export class QueryObserver< return true } - const { notifyOnChangeProps, notifyOnChangePropsExclusions } = this.options + const { notifyOnChangeProps } = this.options - if (!notifyOnChangeProps && !notifyOnChangePropsExclusions) { - return true - } - - if (notifyOnChangeProps === 'tracked' && !this.trackedProps.length) { + if ( + notifyOnChangeProps === 'all' || + (!notifyOnChangeProps && !this.trackedProps.length) + ) { return true } - const includedProps = - notifyOnChangeProps === 'tracked' - ? this.trackedProps - : notifyOnChangeProps + const includedProps = notifyOnChangeProps ?? this.trackedProps return Object.keys(result).some(key => { const typedKey = key as keyof QueryObserverResult const changed = result[typedKey] !== prevResult[typedKey] const isIncluded = includedProps?.some(x => x === key) - const isExcluded = notifyOnChangePropsExclusions?.some(x => x === key) - return changed && !isExcluded && (!includedProps || isIncluded) + return changed && (!includedProps || isIncluded) }) } diff --git a/src/core/types.ts b/src/core/types.ts index 74926e45fe..e9bf309ae4 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -154,13 +154,10 @@ export interface QueryObserverOptions< /** * If set, the component will only re-render if any of the listed properties change. * When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change. - * When set to `tracked`, access to properties will be tracked, and the component will only re-render when one of the tracked properties change. + * When set to `'all'`, the component will re-render whenever a query is updated. + * By default, access to properties will be tracked, and the component will only re-render when one of the tracked properties change. */ - notifyOnChangeProps?: Array | 'tracked' - /** - * If set, the component will not re-render if any of the listed properties change. - */ - notifyOnChangePropsExclusions?: Array + notifyOnChangeProps?: Array | 'all' /** * This callback will fire any time the query successfully fetches new data or the cache is updated via `setQueryData`. */ diff --git a/src/reactjs/tests/QueryResetErrorBoundary.test.tsx b/src/reactjs/tests/QueryResetErrorBoundary.test.tsx index 5fc1e366fe..5e304c6f99 100644 --- a/src/reactjs/tests/QueryResetErrorBoundary.test.tsx +++ b/src/reactjs/tests/QueryResetErrorBoundary.test.tsx @@ -613,7 +613,6 @@ describe('QueryErrorResetBoundary', () => { { retry: false, useErrorBoundary: true, - notifyOnChangeProps: 'tracked', } ) return
{data}
diff --git a/src/reactjs/tests/useInfiniteQuery.test.tsx b/src/reactjs/tests/useInfiniteQuery.test.tsx index 37cb33449a..54865a8c8c 100644 --- a/src/reactjs/tests/useInfiniteQuery.test.tsx +++ b/src/reactjs/tests/useInfiniteQuery.test.tsx @@ -186,6 +186,7 @@ describe('useInfiniteQuery', () => { { getNextPageParam: () => 1, keepPreviousData: true, + notifyOnChangeProps: 'all', } ) @@ -306,6 +307,7 @@ describe('useInfiniteQuery', () => { pages: [...data.pages].reverse(), pageParams: [...data.pageParams].reverse(), }), + notifyOnChangeProps: 'all', } ) @@ -359,6 +361,7 @@ describe('useInfiniteQuery', () => { }, { getPreviousPageParam: firstPage => firstPage - 1, + notifyOnChangeProps: 'all', } ) @@ -423,8 +426,10 @@ describe('useInfiniteQuery', () => { const states: UseInfiniteQueryResult[] = [] function Page() { - const state = useInfiniteQuery(key, ({ pageParam = 10 }) => - Number(pageParam) + const state = useInfiniteQuery( + key, + ({ pageParam = 10 }) => Number(pageParam), + { notifyOnChangeProps: 'all' } ) states.push(state) @@ -516,6 +521,7 @@ describe('useInfiniteQuery', () => { { getPreviousPageParam: firstPage => firstPage - 1, getNextPageParam: lastPage => lastPage + 1, + notifyOnChangeProps: 'all', } ) @@ -608,6 +614,7 @@ describe('useInfiniteQuery', () => { ({ pageParam = 10 }) => Number(pageParam) * multiplier.current, { getNextPageParam: lastPage => lastPage + 1, + notifyOnChangeProps: 'all', } ) @@ -687,6 +694,7 @@ describe('useInfiniteQuery', () => { }, { getNextPageParam: lastPage => lastPage + 1, + notifyOnChangeProps: 'all', } ) @@ -913,6 +921,7 @@ describe('useInfiniteQuery', () => { }, { getNextPageParam: lastPage => lastPage + 1, + notifyOnChangeProps: 'all', } ) @@ -1014,6 +1023,7 @@ describe('useInfiniteQuery', () => { }, { getNextPageParam: lastPage => lastPage + 1, + notifyOnChangeProps: 'all', } ) @@ -1080,6 +1090,7 @@ describe('useInfiniteQuery', () => { }, { getNextPageParam: lastPage => lastPage + 1, + notifyOnChangeProps: 'all', } ) @@ -1169,6 +1180,7 @@ describe('useInfiniteQuery', () => { { initialData: { pages: [1], pageParams: [1] }, getNextPageParam: lastPage => lastPage + 1, + notifyOnChangeProps: 'all', } ) diff --git a/src/reactjs/tests/useQuery.test.tsx b/src/reactjs/tests/useQuery.test.tsx index b8b6a3b704..a86778e14a 100644 --- a/src/reactjs/tests/useQuery.test.tsx +++ b/src/reactjs/tests/useQuery.test.tsx @@ -236,6 +236,7 @@ describe('useQuery', () => { return (

Status: {state.status}

+
Failure Count: {state.failureCount}
) } @@ -373,7 +374,10 @@ describe('useQuery', () => { const onSuccess = jest.fn() function Page() { - const state = useQuery(key, () => 'data', { onSuccess }) + const state = useQuery(key, () => 'data', { + onSuccess, + notifyOnChangeProps: 'all', + }) states.push(state) @@ -738,6 +742,7 @@ describe('useQuery', () => { }, { cacheTime: 0, + notifyOnChangeProps: 'all', } ) @@ -920,54 +925,12 @@ describe('useQuery', () => { consoleMock.mockRestore() }) - it('should re-render when dataUpdatedAt changes but data remains the same', async () => { - const key = queryKey() - const states: UseQueryResult[] = [] - - function Page() { - const state = useQuery(key, () => 'test', { - notifyOnChangePropsExclusions: [ - 'data', - 'isFetching', - 'isLoading', - 'isRefetching', - 'isSuccess', - 'status', - ], - }) - - states.push(state) - - const { refetch } = state - - React.useEffect(() => { - setActTimeout(() => { - refetch() - }, 5) - }, [refetch]) - - return null - } - - renderWithClient(queryClient, ) - - await sleep(10) - - expect(states.length).toBe(3) - expect(states[0]).toMatchObject({ data: undefined, isFetching: true }) - expect(states[1]).toMatchObject({ data: 'test', isFetching: false }) - expect(states[2]).toMatchObject({ data: 'test', isFetching: false }) - expect(states[1]?.dataUpdatedAt).not.toBe(states[2]?.dataUpdatedAt) - }) - it('should track properties and only re-render when a tracked property changes', async () => { const key = queryKey() const states: UseQueryResult[] = [] function Page() { - const state = useQuery(key, () => 'test', { - notifyOnChangeProps: 'tracked', - }) + const state = useQuery(key, () => 'test') states.push(state) @@ -995,46 +958,13 @@ describe('useQuery', () => { expect(states[1]).toMatchObject({ data: 'test' }) }) - it('should not re-render if a tracked prop changes, but it was excluded', async () => { - const key = queryKey() - const states: UseQueryResult[] = [] - - function Page() { - const state = useQuery(key, () => 'test', { - notifyOnChangeProps: 'tracked', - notifyOnChangePropsExclusions: ['data'], - }) - - states.push(state) - - return ( -
-

{state.data ?? 'null'}

-
- ) - } - - const rendered = renderWithClient(queryClient, ) - - await waitFor(() => rendered.getByText('null')) - expect(states.length).toBe(1) - expect(states[0]).toMatchObject({ data: undefined }) - - await queryClient.refetchQueries(key) - await waitFor(() => rendered.getByText('null')) - expect(states.length).toBe(1) - expect(states[0]).toMatchObject({ data: undefined }) - }) - it('should always re-render if we are tracking props but not using any', async () => { const key = queryKey() let renderCount = 0 const states: UseQueryResult[] = [] function Page() { - const state = useQuery(key, () => 'test', { - notifyOnChangeProps: 'tracked', - }) + const state = useQuery(key, () => 'test') states.push(state) @@ -1065,7 +995,7 @@ describe('useQuery', () => { function Page() { const [, rerender] = React.useState({}) - const state = useQuery(key, () => ++count) + const state = useQuery(key, () => ++count, { notifyOnChangeProps: 'all' }) states.push(state) @@ -1106,7 +1036,7 @@ describe('useQuery', () => { let count = 0 function Page() { - const state = useQuery(key, () => ++count) + const state = useQuery(key, () => ++count, { notifyOnChangeProps: 'all' }) states.push(state) @@ -1157,10 +1087,14 @@ describe('useQuery', () => { let count = 0 function Page() { - const state = useQuery(key, () => { - count++ - return count === 1 ? result1 : result2 - }) + const state = useQuery( + key, + () => { + count++ + return count === 1 ? result1 : result2 + }, + { notifyOnChangeProps: 'all' } + ) states.push(state) @@ -1533,6 +1467,7 @@ describe('useQuery', () => {

data: {state.data}

error: {state.error?.message}

+

previous data: {state.isPreviousData}

) } @@ -1694,7 +1629,7 @@ describe('useQuery', () => { await sleep(10) return count }, - { enabled: false, keepPreviousData: true } + { enabled: false, keepPreviousData: true, notifyOnChangeProps: 'all' } ) states.push(state) @@ -1783,7 +1718,7 @@ describe('useQuery', () => { await sleep(10) return count }, - { enabled: false, keepPreviousData: true } + { enabled: false, keepPreviousData: true, notifyOnChangeProps: 'all' } ) states.push(state) @@ -1853,7 +1788,7 @@ describe('useQuery', () => { const states: UseQueryResult[] = [] function FirstComponent() { - const state = useQuery(key, () => 1) + const state = useQuery(key, () => 1, { notifyOnChangeProps: 'all' }) const refetch = state.refetch states.push(state) @@ -1868,7 +1803,7 @@ describe('useQuery', () => { } function SecondComponent() { - useQuery(key, () => 2) + useQuery(key, () => 2, { notifyOnChangeProps: 'all' }) return null } @@ -3637,7 +3572,12 @@ describe('useQuery', () => { states.push(queryInfo) - return
count: {queryInfo.data}
+ return ( +
+

count: {queryInfo.data}

+

refetch: {queryInfo.isRefetching}

+
+ ) } const rendered = renderWithClient(queryClient, ) @@ -4195,7 +4135,7 @@ describe('useQuery', () => { count++ return count }, - { staleTime: Infinity, enabled: false } + { staleTime: Infinity, enabled: false, notifyOnChangeProps: 'all' } ) states.push(state) diff --git a/src/reactjs/useBaseQuery.ts b/src/reactjs/useBaseQuery.ts index 3adb64e053..6853467dca 100644 --- a/src/reactjs/useBaseQuery.ts +++ b/src/reactjs/useBaseQuery.ts @@ -143,7 +143,7 @@ export function useBaseQuery< } // Handle result property usage tracking - if (defaultedOptions.notifyOnChangeProps === 'tracked') { + if (!defaultedOptions.notifyOnChangeProps) { result = observer.trackResult(result, defaultedOptions) }