Skip to content

fix: prevent redundant renders #1487

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 19, 2020
Merged
Show file tree
Hide file tree
Changes from all 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 src/core/queryObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,7 @@ export class QueryObserver<
data,
dataUpdatedAt,
error: state.error,
errorUpdatedAt: state.errorUpdateCount,
errorUpdatedAt: state.errorUpdatedAt,
failureCount: state.fetchFailureCount,
isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
isFetchedAfterMount:
Expand Down
50 changes: 50 additions & 0 deletions src/react/tests/suspense.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,62 @@ import {
QueryCache,
QueryErrorResetBoundary,
useQueryErrorResetBoundary,
UseQueryResult,
} from '../..'

describe("useQuery's in Suspense mode", () => {
const queryCache = new QueryCache()
const queryClient = new QueryClient({ queryCache })

it('should render the correct amount of times in Suspense mode', async () => {
const key = queryKey()
const states: UseQueryResult<number>[] = []

let count = 0
let renders = 0

function Page() {
renders++

const [stateKey, setStateKey] = React.useState(key)

const state = useQuery(
stateKey,
async () => {
count++
await sleep(10)
return count
},
{ suspense: true }
)

states.push(state)

return (
<button aria-label="toggle" onClick={() => setStateKey(queryKey())} />
)
}

const rendered = renderWithClient(
queryClient,
<React.Suspense fallback="loading">
<Page />
</React.Suspense>
)

await sleep(20)

await waitFor(() => rendered.getByLabelText('toggle'))
fireEvent.click(rendered.getByLabelText('toggle'))

await sleep(20)

expect(renders).toBe(4)
expect(states.length).toBe(2)
expect(states[0]).toMatchObject({ data: 1, status: 'success' })
expect(states[1]).toMatchObject({ data: 2, status: 'success' })
})

it('should not call the queryFn twice when used in Suspense mode', async () => {
const key = queryKey()

Expand Down
23 changes: 4 additions & 19 deletions src/react/tests/useInfiniteQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ describe('useInfiniteQuery', () => {

await sleep(300)

expect(states.length).toBe(7)
expect(states.length).toBe(6)
expect(states[0]).toMatchObject({
data: undefined,
isFetching: true,
Expand Down Expand Up @@ -244,13 +244,6 @@ describe('useInfiniteQuery', () => {
isPreviousData: true,
})
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,
Expand Down Expand Up @@ -823,7 +816,7 @@ describe('useInfiniteQuery', () => {

await sleep(100)

expect(states.length).toBe(6)
expect(states.length).toBe(5)
expect(states[0]).toMatchObject({
hasNextPage: undefined,
data: undefined,
Expand All @@ -847,24 +840,16 @@ describe('useInfiniteQuery', () => {
isFetchingNextPage: false,
isSuccess: true,
})
// Cache update
expect(states[3]).toMatchObject({
hasNextPage: true,
data: { pages: [7, 8] },
isFetching: false,
isFetchingNextPage: false,
isSuccess: true,
})
// Refetch
expect(states[4]).toMatchObject({
expect(states[3]).toMatchObject({
hasNextPage: true,
data: { pages: [7, 8] },
isFetching: true,
isFetchingNextPage: false,
isSuccess: true,
})
// Refetch done
expect(states[5]).toMatchObject({
expect(states[4]).toMatchObject({
hasNextPage: true,
data: { pages: [7, 8] },
isFetching: false,
Expand Down
70 changes: 18 additions & 52 deletions src/react/tests/useQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -568,17 +568,15 @@ describe('useQuery', () => {

await sleep(100)

expect(states.length).toBe(5)
expect(states.length).toBe(4)
// First load
expect(states[0]).toMatchObject({ isLoading: true, isSuccess: false })
// First success
expect(states[1]).toMatchObject({ isLoading: false, isSuccess: true })
// Switch
expect(states[2]).toMatchObject({ isLoading: true, isSuccess: false })
// Second load
expect(states[3]).toMatchObject({ isLoading: true, isSuccess: false })
expect(states[2]).toMatchObject({ isLoading: true, isSuccess: false })
// Second success
expect(states[4]).toMatchObject({ isLoading: false, isSuccess: true })
expect(states[3]).toMatchObject({ isLoading: false, isSuccess: true })
})

it('should fetch when refetchOnMount is false and nothing has been fetched yet', async () => {
Expand Down Expand Up @@ -768,17 +766,15 @@ describe('useQuery', () => {

await sleep(20)

expect(states.length).toBe(5)
expect(states.length).toBe(4)
// Initial
expect(states[0]).toMatchObject({ data: undefined })
// Fetched
expect(states[1]).toMatchObject({ data: 1 })
// Rerender
expect(states[2]).toMatchObject({ data: undefined })
// Switch
expect(states[3]).toMatchObject({ data: undefined })
expect(states[2]).toMatchObject({ data: undefined })
// Fetched
expect(states[4]).toMatchObject({ data: 2 })
expect(states[3]).toMatchObject({ data: 2 })
})

it('should be create a new query when refetching a removed query', async () => {
Expand Down Expand Up @@ -1084,7 +1080,7 @@ describe('useQuery', () => {

renderWithClient(queryClient, <Page />)

await waitFor(() => expect(states.length).toBe(5))
await waitFor(() => expect(states.length).toBe(4))

// Initial
expect(states[0]).toMatchObject({
Expand All @@ -1107,15 +1103,8 @@ describe('useQuery', () => {
isSuccess: true,
isPreviousData: true,
})
// Previous data
expect(states[3]).toMatchObject({
data: 0,
isFetching: true,
isSuccess: true,
isPreviousData: true,
})
// New data
expect(states[4]).toMatchObject({
expect(states[3]).toMatchObject({
data: 1,
isFetching: false,
isSuccess: true,
Expand Down Expand Up @@ -1152,7 +1141,7 @@ describe('useQuery', () => {

renderWithClient(queryClient, <Page />)

await waitFor(() => expect(states.length).toBe(5))
await waitFor(() => expect(states.length).toBe(4))

// Initial
expect(states[0]).toMatchObject({
Expand All @@ -1175,15 +1164,8 @@ describe('useQuery', () => {
isSuccess: true,
isPreviousData: true,
})
// Previous data
expect(states[3]).toMatchObject({
data: 0,
isFetching: true,
isSuccess: true,
isPreviousData: true,
})
// New data
expect(states[4]).toMatchObject({
expect(states[3]).toMatchObject({
data: 1,
isFetching: false,
isSuccess: true,
Expand Down Expand Up @@ -1228,7 +1210,7 @@ describe('useQuery', () => {

renderWithClient(queryClient, <Page />)

await waitFor(() => expect(states.length).toBe(7))
await waitFor(() => expect(states.length).toBe(6))

// Disabled query
expect(states[0]).toMatchObject({
Expand Down Expand Up @@ -1258,22 +1240,15 @@ describe('useQuery', () => {
isSuccess: true,
isPreviousData: true,
})
// Switched query key
expect(states[4]).toMatchObject({
data: 0,
isFetching: false,
isSuccess: true,
isPreviousData: true,
})
// Fetching new query
expect(states[5]).toMatchObject({
expect(states[4]).toMatchObject({
data: 0,
isFetching: true,
isSuccess: true,
isPreviousData: true,
})
// Fetched new query
expect(states[6]).toMatchObject({
expect(states[5]).toMatchObject({
data: 1,
isFetching: false,
isSuccess: true,
Expand Down Expand Up @@ -1324,7 +1299,7 @@ describe('useQuery', () => {

await sleep(100)

expect(states.length).toBe(6)
expect(states.length).toBe(5)

// Disabled query
expect(states[0]).toMatchObject({
Expand All @@ -1340,29 +1315,22 @@ describe('useQuery', () => {
isSuccess: true,
isPreviousData: true,
})
// Switched query key
expect(states[2]).toMatchObject({
data: 10,
isFetching: false,
isSuccess: true,
isPreviousData: true,
})
// Set state
expect(states[3]).toMatchObject({
expect(states[2]).toMatchObject({
data: 10,
isFetching: false,
isSuccess: true,
isPreviousData: true,
})
// Switched query key
expect(states[4]).toMatchObject({
expect(states[3]).toMatchObject({
data: 10,
isFetching: true,
isSuccess: true,
isPreviousData: true,
})
// Refetch done
expect(states[5]).toMatchObject({
expect(states[4]).toMatchObject({
data: 12,
isFetching: false,
isSuccess: true,
Expand Down Expand Up @@ -2126,13 +2094,11 @@ describe('useQuery', () => {

await sleep(100)

expect(states.length).toBe(3)
expect(states.length).toBe(2)
// Initial
expect(states[0]).toMatchObject({ data: { count: 0 } })
// Set state
expect(states[1]).toMatchObject({ data: { count: 1 } })
// Update
expect(states[2]).toMatchObject({ data: { count: 1 } })
})

it('should retry specified number of times', async () => {
Expand Down
13 changes: 12 additions & 1 deletion src/react/useBaseQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ 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'
Expand Down Expand Up @@ -56,10 +57,20 @@ export function useBaseQuery<TQueryFnData, TError, TData, TQueryData>(
const [, rerender] = React.useState({})
const currentResult = observer.getCurrentResult()

// Remember latest result to prevent redundant renders
const latestResultRef = React.useRef(currentResult)
latestResultRef.current = currentResult

// Subscribe to the observer
React.useEffect(() => {
errorResetBoundary.clearReset()
return observer.subscribe(notifyManager.batchCalls(rerender))
return observer.subscribe(
notifyManager.batchCalls((result: QueryObserverResult) => {
if (result !== latestResultRef.current) {
rerender({})
}
})
)
}, [observer, errorResetBoundary])

// Handle suspense
Expand Down