Repository: tannerlinsley/react-query
Pull request #1609 (2021-01-09 15:44:57)

docs: mention query options strictly for useQuery
This is in accordance with issues faced when trying use certain query options in `prefetchQuery` and `prefetchInfiniteQuery`. I opened a [discussion](https://github.com/tannerlinsley/react-query/discussions/1596) and was [suggested](https://github.com/tannerlinsley/react-query/discussions/1596#discussioncomment-267856) to open a PR to mention/describe the options available.

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/9a366j8aq](https://vercel.com/tannerlinsley/react-query/9a366j8aq)  
✅ Preview: *In Progress*



Patch:
diff --git a/docs/src/pages/guides/initial-query-data.md b/docs/src/pages/guides/initial-query-data.md
index 66fc88bda..01d62899f 100644
--- a/docs/src/pages/guides/initial-query-data.md
+++ b/docs/src/pages/guides/initial-query-data.md
@@ -44,7 +44,7 @@ By default, `initialData` is treated as totally fresh, as if it were just fetche
 
   ```js
   function Todos() {
-    // Show initialTodos immeidately, but won't refetch until another interaction event is encountered after 1000 ms
+    // Show initialTodos immediately, but won't refetch until another interaction event is encountered after 1000 ms
     const result = useQuery('todos', () => fetch('/todos'), {
       initialData: initialTodos,
       staleTime: 1000,
diff --git a/docs/src/pages/guides/mutations.md b/docs/src/pages/guides/mutations.md
index f593d82f8..769e7f806 100644
--- a/docs/src/pages/guides/mutations.md
+++ b/docs/src/pages/guides/mutations.md
@@ -5,7 +5,7 @@ title: Mutations
 
 Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, React Query exports a `useMutation` hook.
 
-Here's an example of a mutation that adds a new todo the server:
+Here's an example of a mutation that adds a new todo to the server:
 
 ```js
 function App() {
diff --git a/docs/src/pages/guides/query-invalidation.md b/docs/src/pages/guides/query-invalidation.md
index 3f342c077..af2d31959 100644
--- a/docs/src/pages/guides/query-invalidation.md
+++ b/docs/src/pages/guides/query-invalidation.md
@@ -17,7 +17,7 @@ queryClient.invalidateQueries('todos')
 When a query is invalidated with `invalidateQueries`, two things happen:
 
 - It is marked as stale. This stale state overrides any `staleTime` configurations being used in `useQuery` or related hooks
-- If the query is currently being rendered via `useQuery` or related hooks), it will also be refetched in the background
+- If the query is currently being rendered via `useQuery` or related hooks, it will also be refetched in the background
 
 ## Query Matching with `invalidateQueries`
 
diff --git a/docs/src/pages/reference/QueryClient.md b/docs/src/pages/reference/QueryClient.md
index e7e4220ad..b6847850a 100644
--- a/docs/src/pages/reference/QueryClient.md
+++ b/docs/src/pages/reference/QueryClient.md
@@ -88,7 +88,7 @@ try {
 
 **Options**
 
-The options for `fetchQuery` are exactly the same as those of [`useQuery`](#usequery).
+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 stictly 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**
 
@@ -109,7 +109,7 @@ try {
 
 **Options**
 
-The options for `fetchInfiniteQuery` are exactly the same as those of [`useInfiniteQuery`](#useinfinitequery).
+The options for `fetchInfiniteQuery` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery).
 
 **Returns**
 
@@ -131,7 +131,7 @@ await queryClient.prefetchQuery(queryKey)
 
 **Options**
 
-The options for `prefetchQuery` are exactly the same as those of [`useQuery`](#usequery).
+The options for `prefetchQuery` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery).
 
 **Returns**
 
@@ -148,7 +148,7 @@ await queryClient.prefetchInfiniteQuery(queryKey, queryFn)
 
 **Options**
 
-The options for `prefetchInfiniteQuery` are exactly the same as those of [`useInfiniteQuery`](#useinfinitequery).
+The options for `prefetchInfiniteQuery` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery).
 
 **Returns**
 
diff --git a/src/react/useBaseQuery.ts b/src/react/useBaseQuery.ts
index efa0e7742..05c7becdd 100644
--- a/src/react/useBaseQuery.ts
+++ b/src/react/useBaseQuery.ts
@@ -2,7 +2,6 @@ import React from 'react'
 
 import { notifyManager } from '../core/notifyManager'
 import { QueryObserver } from '../core/queryObserver'
-import { QueryObserverResult } from '../core/types'
 import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'
 import { useQueryClient } from './QueryClientProvider'
 import { UseBaseQueryOptions } from './types'
@@ -59,23 +58,12 @@ export function useBaseQuery<TQueryFnData, TError, TData, TQueryData>(
   }
 
   const currentResult = observer.getCurrentResult()
-
-  // Remember latest result to prevent redundant renders
-  const latestResultRef = React.useRef(currentResult)
-  latestResultRef.current = currentResult
-
-  const [, rerender] = React.useState({})
+  const [, setCurrentResult] = React.useState(currentResult)
 
   // Subscribe to the observer
   React.useEffect(() => {
     errorResetBoundary.clearReset()
-    return observer.subscribe(
-      notifyManager.batchCalls((result: QueryObserverResult) => {
-        if (result !== latestResultRef.current) {
-          rerender({})
-        }
-      })
-    )
+    return observer.subscribe(notifyManager.batchCalls(setCurrentResult))
   }, [observer, errorResetBoundary])
 
   // Handle suspense


Test patch:
diff --git a/docs/src/pages/guides/testing.md b/docs/src/pages/guides/testing.md
index d6cb414b5..9b0b5bdcc 100644
--- a/docs/src/pages/guides/testing.md
+++ b/docs/src/pages/guides/testing.md
@@ -29,11 +29,11 @@ export function useCustomHook() {
 We can write a test for this as follows:
 
 ```
-const queryCache = new QueryCache();
+const queryClient = new QueryClient();
 const wrapper = ({ children }) => (
-  <ReactQueryCacheProvider queryCache={queryCache}>
+  <QueryClientProvider client={queryClient}>
     {children}
-  </ReactQueryCacheProvider>
+  </QueryClientProvider>
 );
 
 const { result } = renderHook(() => useCustomHook(), { wrapper });
@@ -41,9 +41,9 @@ const { result } = renderHook(() => useCustomHook(), { wrapper });
 expect(result.current).toEqual('Hello');
 ```
 
-Note that we provide a custom wrapper that builds the `QueryCache` and `ReactQueryCacheProvider`. This helps to ensure that our test is completely isolated from any other tests.
+Note that we provide a custom wrapper that builds the `QueryClient` and `QueryClientProvider`. This helps to ensure that our test is completely isolated from any other tests.
 
-It is possible to write this wrapper only once, but if so we need to ensure that the `QueryCache` gets cleared before every test, and that tests don't run in parallel otherwise one test will influence the results of others.
+It is possible to write this wrapper only once, but if so we need to ensure that the `QueryClient` gets cleared before every test, and that tests don't run in parallel otherwise one test will influence the results of others.
 
 ## Testing Network Calls
 
@@ -62,11 +62,11 @@ function useFetchData() {
 We can write a test for this as follows:
 
 ```
-const queryCache = new QueryCache();
+const queryClient = new QueryClient();
 const wrapper = ({ children }) => (
-  <ReactQueryCacheProvider queryCache={queryCache}>
+  <QueryClientProvider client={queryClient}>
     {children}
-  </ReactQueryCacheProvider>
+  </QueryClientProvider>
 );
 
 const expectation = nock('http://example.com')
diff --git a/src/react/tests/suspense.test.tsx b/src/react/tests/suspense.test.tsx
index a8534bc88..da6638e94 100644
--- a/src/react/tests/suspense.test.tsx
+++ b/src/react/tests/suspense.test.tsx
@@ -59,7 +59,7 @@ describe("useQuery's in Suspense mode", () => {
 
     await sleep(20)
 
-    expect(renders).toBe(4)
+    expect(renders).toBe(5)
     expect(states.length).toBe(2)
     expect(states[0]).toMatchObject({ data: 1, status: 'success' })
     expect(states[1]).toMatchObject({ data: 2, status: 'success' })
diff --git a/src/react/tests/useInfiniteQuery.test.tsx b/src/react/tests/useInfiniteQuery.test.tsx
index f9d8333e8..ddc1e25f2 100644
--- a/src/react/tests/useInfiniteQuery.test.tsx
+++ b/src/react/tests/useInfiniteQuery.test.tsx
@@ -206,7 +206,7 @@ describe('useInfiniteQuery', () => {
 
     await sleep(300)
 
-    expect(states.length).toBe(6)
+    expect(states.length).toBe(7)
     expect(states[0]).toMatchObject({
       data: undefined,
       isFetching: true,
@@ -243,7 +243,15 @@ describe('useInfiniteQuery', () => {
       isSuccess: true,
       isPreviousData: true,
     })
+    // Hook state update
     expect(states[5]).toMatchObject({
+      data: { pages: ['0-desc', '1-desc'] },
+      isFetching: true,
+      isFetchingNextPage: false,
+      isSuccess: true,
+      isPreviousData: true,
+    })
+    expect(states[6]).toMatchObject({
       data: { pages: ['0-asc'] },
       isFetching: false,
       isFetchingNextPage: false,
@@ -816,7 +824,7 @@ describe('useInfiniteQuery', () => {
 
     await sleep(100)
 
-    expect(states.length).toBe(5)
+    expect(states.length).toBe(6)
     expect(states[0]).toMatchObject({
       hasNextPage: undefined,
       data: undefined,
@@ -840,8 +848,16 @@ describe('useInfiniteQuery', () => {
       isFetchingNextPage: false,
       isSuccess: true,
     })
-    // Refetch
+    // Hook state update
     expect(states[3]).toMatchObject({
+      hasNextPage: true,
+      data: { pages: [7, 8] },
+      isFetching: false,
+      isFetchingNextPage: false,
+      isSuccess: true,
+    })
+    // Refetch
+    expect(states[4]).toMatchObject({
       hasNextPage: true,
       data: { pages: [7, 8] },
       isFetching: true,
@@ -849,7 +865,7 @@ describe('useInfiniteQuery', () => {
       isSuccess: true,
     })
     // Refetch done
-    expect(states[4]).toMatchObject({
+    expect(states[5]).toMatchObject({
       hasNextPage: true,
       data: { pages: [7, 8] },
       isFetching: false,
diff --git a/src/react/tests/useQuery.test.tsx b/src/react/tests/useQuery.test.tsx
index cd879164c..3848e5a87 100644
--- a/src/react/tests/useQuery.test.tsx
+++ b/src/react/tests/useQuery.test.tsx
@@ -568,15 +568,17 @@ describe('useQuery', () => {
 
     await sleep(100)
 
-    expect(states.length).toBe(4)
+    expect(states.length).toBe(5)
     // First load
     expect(states[0]).toMatchObject({ isLoading: true, isSuccess: false })
     // First success
     expect(states[1]).toMatchObject({ isLoading: false, isSuccess: true })
-    // Second load
+    // Remove
     expect(states[2]).toMatchObject({ isLoading: true, isSuccess: false })
+    // Hook state update
+    expect(states[3]).toMatchObject({ isLoading: true, isSuccess: false })
     // Second success
-    expect(states[3]).toMatchObject({ isLoading: false, isSuccess: true })
+    expect(states[4]).toMatchObject({ isLoading: false, isSuccess: true })
   })
 
   it('should fetch when refetchOnMount is false and nothing has been fetched yet', async () => {
@@ -766,15 +768,17 @@ describe('useQuery', () => {
 
     await sleep(20)
 
-    expect(states.length).toBe(4)
+    expect(states.length).toBe(5)
     // Initial
     expect(states[0]).toMatchObject({ data: undefined })
     // Fetched
     expect(states[1]).toMatchObject({ data: 1 })
-    // Switch
+    // Remove
     expect(states[2]).toMatchObject({ data: undefined })
+    // Hook state update
+    expect(states[3]).toMatchObject({ data: undefined })
     // Fetched
-    expect(states[3]).toMatchObject({ data: 2 })
+    expect(states[4]).toMatchObject({ data: 2 })
   })
 
   it('should be create a new query when refetching a removed query', async () => {
@@ -1080,7 +1084,7 @@ describe('useQuery', () => {
 
     renderWithClient(queryClient, <Page />)
 
-    await waitFor(() => expect(states.length).toBe(4))
+    await waitFor(() => expect(states.length).toBe(5))
 
     // Initial
     expect(states[0]).toMatchObject({
@@ -1103,8 +1107,15 @@ describe('useQuery', () => {
       isSuccess: true,
       isPreviousData: true,
     })
-    // New data
+    // Hook state update
     expect(states[3]).toMatchObject({
+      data: 0,
+      isFetching: true,
+      isSuccess: true,
+      isPreviousData: true,
+    })
+    // New data
+    expect(states[4]).toMatchObject({
       data: 1,
       isFetching: false,
       isSuccess: true,
@@ -1141,7 +1152,7 @@ describe('useQuery', () => {
 
     renderWithClient(queryClient, <Page />)
 
-    await waitFor(() => expect(states.length).toBe(4))
+    await waitFor(() => expect(states.length).toBe(5))
 
     // Initial
     expect(states[0]).toMatchObject({
@@ -1164,8 +1175,15 @@ describe('useQuery', () => {
       isSuccess: true,
       isPreviousData: true,
     })
-    // New data
+    // Hook state update
     expect(states[3]).toMatchObject({
+      data: 0,
+      isFetching: true,
+      isSuccess: true,
+      isPreviousData: true,
+    })
+    // New data
+    expect(states[4]).toMatchObject({
       data: 1,
       isFetching: false,
       isSuccess: true,
@@ -1210,7 +1228,7 @@ describe('useQuery', () => {
 
     renderWithClient(queryClient, <Page />)
 
-    await waitFor(() => expect(states.length).toBe(6))
+    await waitFor(() => expect(states.length).toBe(7))
 
     // Disabled query
     expect(states[0]).toMatchObject({
@@ -1240,15 +1258,22 @@ describe('useQuery', () => {
       isSuccess: true,
       isPreviousData: true,
     })
-    // Fetching new query
+    // Hook state update
     expect(states[4]).toMatchObject({
+      data: 0,
+      isFetching: false,
+      isSuccess: true,
+      isPreviousData: true,
+    })
+    // Fetching new query
+    expect(states[5]).toMatchObject({
       data: 0,
       isFetching: true,
       isSuccess: true,
       isPreviousData: true,
     })
     // Fetched new query
-    expect(states[5]).toMatchObject({
+    expect(states[6]).toMatchObject({
       data: 1,
       isFetching: false,
       isSuccess: true,
@@ -1299,7 +1324,7 @@ describe('useQuery', () => {
 
     await sleep(100)
 
-    expect(states.length).toBe(5)
+    expect(states.length).toBe(6)
 
     // Disabled query
     expect(states[0]).toMatchObject({
@@ -1322,15 +1347,22 @@ describe('useQuery', () => {
       isSuccess: true,
       isPreviousData: true,
     })
-    // Switched query key
+    // Hook state update
     expect(states[3]).toMatchObject({
+      data: 10,
+      isFetching: false,
+      isSuccess: true,
+      isPreviousData: true,
+    })
+    // Refetch
+    expect(states[4]).toMatchObject({
       data: 10,
       isFetching: true,
       isSuccess: true,
       isPreviousData: true,
     })
     // Refetch done
-    expect(states[4]).toMatchObject({
+    expect(states[5]).toMatchObject({
       data: 12,
       isFetching: false,
       isSuccess: true,
@@ -1690,6 +1722,27 @@ describe('useQuery', () => {
     expect(renderedCount).toBe(2)
   })
 
+  it('should render latest data even if react has discarded certain renders', async () => {
+    const key = queryKey()
+
+    function Page() {
+      const [, setNewState] = React.useState('state')
+      const state = useQuery(key, () => 'data')
+      React.useEffect(() => {
+        setActTimeout(() => {
+          queryClient.setQueryData(key, 'new')
+          // Update with same state to make react discard the next render
+          setNewState('state')
+        }, 10)
+      }, [])
+      return <div>{state.data}</div>
+    }
+
+    const rendered = renderWithClient(queryClient, <Page />)
+
+    await waitFor(() => rendered.getByText('new'))
+  })
+
   // See https://github.com/tannerlinsley/react-query/issues/170
   it('should start with status idle if enabled is false', async () => {
     const key1 = queryKey()
@@ -2163,11 +2216,13 @@ describe('useQuery', () => {
 
     await sleep(100)
 
-    expect(states.length).toBe(2)
+    expect(states.length).toBe(3)
     // Initial
     expect(states[0]).toMatchObject({ data: { count: 0 } })
     // Set state
     expect(states[1]).toMatchObject({ data: { count: 1 } })
+    // Hook state update
+    expect(states[2]).toMatchObject({ data: { count: 1 } })
   })
 
   it('should retry specified number of times', async () => {