Repository: tannerlinsley/react-query
Pull request #1676 (2021-01-21 19:54:40)

docs: add v2 docs links
Since folks are still on v2 and asking about those docs this adds a couple front-facing spots to find them: 

1. main repo README
2. main RQ docs nav

<img width="506" alt="Screen Shot 2021-01-21 at 2 37 19 PM" src="https://user-images.githubusercontent.com/14936212/105404681-3e4a3600-5bf8-11eb-8a6c-3fe2da70a5fc.png">


vercel[bot]: This pull request is being automatically deployed with Vercel ([learn more](https://vercel.link/github-learn-more)).  
To see the status of your deployment, click below or on the icon next to each commit.

🔍 Inspect: [https://vercel.com/tannerlinsley/react-query/a205ta0bt](https://vercel.com/tannerlinsley/react-query/a205ta0bt)  
✅ Preview: *In Progress*


TkDodo: Awesome. Minor thing: it doesn’t look so good on mobile, and it’s hard to know on which docs I am because v3 is not “highlighted”:
![7CEB8CBA-3326-4BE3-AA42-AB36FEC9592C](https://user-images.githubusercontent.com/1021430/105406914-5be5c280-5c2d-11eb-8779-28cd6cec720a.jpeg)

babycourageous: Ah - you're totally right. My initial preview wasn't small enough to catch that. 

I like what Tailwind does - 
![image](https://user-images.githubusercontent.com/14936212/105407550-dd246180-5bfb-11eb-8b64-ea0b1290d496.png)

What do you think of keeping NAV as originally was - but putting a line on the homepage (like I did for README) that basically says "Still on v2? Check out the v2 docs here: LINK"
TkDodo: Yep, that sounds good
babycourageous: B4 pushing - how's this?

sm: 

![image](https://user-images.githubusercontent.com/14936212/105410318-bec06500-5bff-11eb-8d1a-a23ebfd773ae.png)

md: 

![image](https://user-images.githubusercontent.com/14936212/105410350-cd0e8100-5bff-11eb-9100-f15577e30ecd.png)

lg:

![image](https://user-images.githubusercontent.com/14936212/105410374-d861ac80-5bff-11eb-95e1-e652f1331402.png)

TkDodo: I'd put the link under `here` because now it says `v2` 3 times in the same sentence 😅 . Or even like this:

Still using v2? No problem! [Find the v2 docs here](https://react-query-v2.tanstack.com/).

Patch:
diff --git a/README.md b/README.md
index 143934d1d..1ff558d1d 100644
--- a/README.md
+++ b/README.md
@@ -28,6 +28,7 @@ Enjoy this library? Try the entire [TanStack](https://tanstack.com)! [React Tabl
 
 ## Visit [react-query.tanstack.com](https://react-query.tanstack.com) for docs, guides, API and more!
 
+Still on **React Query v2**? No problem! Check out the v2 docs here: https://react-query-v2.tanstack.com/.
 ## Quick Features
 
 - Transport/protocol/backend agnostic data fetching (REST, GraphQL, promises, whatever!)
diff --git a/docs/src/pages/comparison.md b/docs/src/pages/comparison.md
index 34ca529ca..ce8c08c19 100644
--- a/docs/src/pages/comparison.md
+++ b/docs/src/pages/comparison.md
@@ -63,7 +63,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']`. Set `notifyOnChangeProps: 'tracked'` 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.
 
diff --git a/docs/src/pages/index.js b/docs/src/pages/index.js
index ac6a1896e..a5e1ea256 100644
--- a/docs/src/pages/index.js
+++ b/docs/src/pages/index.js
@@ -85,6 +85,17 @@ const Home = ({ sponsors }) => {
                       </a>
                     </div>
                   </div>
+                  <div className="mt-5">
+                    <p>
+                      Still using v2? No problem!{' '}
+                      <a
+                        href="https://react-query-v2.tanstack.com/docs/overview"
+                        className="text-blue-600 font-semibold transition-colors duration-150 ease-out"
+                      >
+                        Find the v2 docs here.
+                      </a>
+                    </p>
+                  </div>
                 </div>
               </div>
             </div>
diff --git a/docs/src/pages/reference/useQuery.md b/docs/src/pages/reference/useQuery.md
index d8a1bc474..9cb8be065 100644
--- a/docs/src/pages/reference/useQuery.md
+++ b/docs/src/pages/reference/useQuery.md
@@ -39,7 +39,7 @@ const {
   refetchOnWindowFocus,
   retry,
   retryDelay,
-  select
+  select,
   staleTime,
   structuralSharing,
   suspense,
@@ -109,10 +109,11 @@ 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[]`
+- `notifyOnChangeProps: string[] | "tracked"`
   - 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.
diff --git a/src/core/queryObserver.ts b/src/core/queryObserver.ts
index e40d5cc76..986326aab 100644
--- a/src/core/queryObserver.ts
+++ b/src/core/queryObserver.ts
@@ -54,6 +54,8 @@ export class QueryObserver<
   private initialErrorUpdateCount: number
   private staleTimeoutId?: number
   private refetchIntervalId?: number
+  private trackedProps!: Array<keyof QueryObserverResult>
+  private trackedCurrentResult!: QueryObserverResult<TData, TError>
 
   constructor(
     client: QueryClient,
@@ -65,6 +67,7 @@ export class QueryObserver<
     this.options = options
     this.initialDataUpdateCount = 0
     this.initialErrorUpdateCount = 0
+    this.trackedProps = []
     this.bindMethods()
     this.setOptions(options)
   }
@@ -208,6 +211,10 @@ export class QueryObserver<
     return this.currentResult
   }
 
+  getTrackedCurrentResult(): QueryObserverResult<TData, TError> {
+    return this.trackedCurrentResult
+  }
+
   getNextResult(
     options?: ResultOptions
   ): Promise<QueryObserverResult<TData, TError>> {
@@ -449,11 +456,15 @@ export class QueryObserver<
     }
 
     const keys = Object.keys(result)
+    const includedProps =
+      notifyOnChangeProps === 'tracked'
+        ? this.trackedProps
+        : notifyOnChangeProps
 
     for (let i = 0; i < keys.length; i++) {
       const key = keys[i] as keyof QueryObserverResult
       const changed = prevResult[key] !== result[key]
-      const isIncluded = notifyOnChangeProps?.some(x => x === key)
+      const isIncluded = includedProps?.some(x => x === key)
       const isExcluded = notifyOnChangePropsExclusions?.some(x => x === key)
 
       if (changed) {
@@ -461,7 +472,11 @@ export class QueryObserver<
           continue
         }
 
-        if (!notifyOnChangeProps || isIncluded) {
+        if (
+          !notifyOnChangeProps ||
+          isIncluded ||
+          (notifyOnChangeProps === 'tracked' && this.trackedProps.length === 0)
+        ) {
           return true
         }
       }
@@ -479,6 +494,26 @@ export class QueryObserver<
     // Only update if something has changed
     if (!shallowEqualObjects(result, this.currentResult)) {
       this.currentResult = result
+
+      if (this.options.notifyOnChangeProps === 'tracked') {
+        const addTrackedProps = (prop: keyof QueryObserverResult) => {
+          if (!this.trackedProps.includes(prop)) {
+            this.trackedProps.push(prop)
+          }
+        }
+        this.trackedCurrentResult = {} as QueryObserverResult<TData, TError>
+
+        Object.keys(result).forEach(key => {
+          Object.defineProperty(this.trackedCurrentResult, key, {
+            configurable: false,
+            enumerable: true,
+            get() {
+              addTrackedProps(key as keyof QueryObserverResult)
+              return result[key as keyof QueryObserverResult]
+            },
+          })
+        })
+      }
     }
   }
 
diff --git a/src/core/types.ts b/src/core/types.ts
index 7ad1fd1e8..9cabdcc2a 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -136,8 +136,9 @@ 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.
    */
-  notifyOnChangeProps?: Array<keyof InfiniteQueryObserverResult>
+  notifyOnChangeProps?: Array<keyof InfiniteQueryObserverResult> | 'tracked'
   /**
    * If set, the component will not re-render if any of the listed properties change.
    */
diff --git a/src/react/useBaseQuery.ts b/src/react/useBaseQuery.ts
index 05c7becdd..c75338b5a 100644
--- a/src/react/useBaseQuery.ts
+++ b/src/react/useBaseQuery.ts
@@ -79,5 +79,7 @@ export function useBaseQuery<TQueryFnData, TError, TData, TQueryData>(
     }
   }
 
-  return currentResult
+  return observer.options.notifyOnChangeProps === 'tracked'
+    ? observer.getTrackedCurrentResult()
+    : currentResult
 }


Test patch:
diff --git a/src/react/tests/useQuery.test.tsx b/src/react/tests/useQuery.test.tsx
index 67d21e6ef..472bd6166 100644
--- a/src/react/tests/useQuery.test.tsx
+++ b/src/react/tests/useQuery.test.tsx
@@ -739,6 +739,146 @@ 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 () => {
+    const key = queryKey()
+    const states: UseQueryResult<string>[] = []
+
+    function Page() {
+      const state = useQuery(key, () => 'test', {
+        notifyOnChangeProps: 'tracked',
+      })
+
+      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 not re-render if a tracked prop changes, but it was excluded', async () => {
+    const key = queryKey()
+    const states: UseQueryResult<string>[] = []
+
+    function Page() {
+      const state = useQuery(key, () => 'test', {
+        notifyOnChangeProps: 'tracked',
+        notifyOnChangePropsExclusions: ['data'],
+      })
+
+      states.push(state)
+
+      return (
+        <div>
+          <h1>{state.data ?? 'null'}</h1>
+        </div>
+      )
+    }
+
+    const rendered = renderWithClient(queryClient, <Page />)
+
+    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 return the referentially same object if nothing changes between fetches', async () => {
+    const key = queryKey()
+    let renderCount = 0
+    const states: UseQueryResult<string>[] = []
+
+    function Page() {
+      const state = useQuery(key, () => 'test', {
+        notifyOnChangeProps: 'tracked',
+      })
+
+      states.push(state)
+
+      const { data } = state
+
+      React.useEffect(() => {
+        renderCount++
+      }, [state])
+
+      return (
+        <div>
+          <h1>{data ?? null}</h1>
+        </div>
+      )
+    }
+
+    const rendered = renderWithClient(queryClient, <Page />)
+
+    await waitFor(() => rendered.getByText('test'))
+    expect(renderCount).toBe(2)
+    expect(states.length).toBe(2)
+    expect(states[0]).toMatchObject({ data: undefined })
+    expect(states[1]).toMatchObject({ data: 'test' })
+
+    act(() => rendered.rerender(<Page />))
+    await waitFor(() => rendered.getByText('test'))
+    expect(renderCount).toBe(2)
+    expect(states.length).toBe(3)
+    expect(states[0]).toMatchObject({ data: undefined })
+    expect(states[1]).toMatchObject({ data: 'test' })
+    expect(states[2]).toMatchObject({ data: 'test' })
+  })
+
+  it('should always re-render if we are tracking props but not using any', async () => {
+    const key = queryKey()
+    let renderCount = 0
+    const states: UseQueryResult<string>[] = []
+
+    function Page() {
+      const state = useQuery(key, () => 'test', {
+        notifyOnChangeProps: 'tracked',
+      })
+
+      states.push(state)
+
+      React.useEffect(() => {
+        renderCount++
+      }, [state])
+
+      return (
+        <div>
+          <h1>hello</h1>
+        </div>
+      )
+    }
+
+    renderWithClient(queryClient, <Page />)
+
+    await waitFor(() => renderCount > 1)
+    expect(renderCount).toBe(2)
+    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>[] = []