Skip to content
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

Fixed memory leak in rapid hook arg changing #4268

Merged
merged 8 commits into from
Mar 18, 2024
17 changes: 17 additions & 0 deletions packages/toolkit/src/query/core/buildMiddleware/cacheCollection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export const THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2_147_483_647 / 1_000 - 1
export const buildCacheCollectionHandler: InternalHandlerBuilder = ({
reducerPath,
api,
queryThunk,
context,
internalState,
}) => {
Expand Down Expand Up @@ -100,6 +101,22 @@ export const buildCacheCollectionHandler: InternalHandlerBuilder = ({
)
}
}

if (
queryThunk.fulfilled.match(action) ||
queryThunk.rejected.match(action)
) {
const state = mwApi.getState()[reducerPath]
const queryCacheKey = action.meta.arg.queryCacheKey
riqts marked this conversation as resolved.
Show resolved Hide resolved

handleUnsubscribe(
queryCacheKey,
state.queries[queryCacheKey]?.endpointName,
mwApi,
state.config
)

}
}

function handleUnsubscribe(
Expand Down
54 changes: 54 additions & 0 deletions packages/toolkit/src/query/tests/buildHooks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -730,6 +730,60 @@ describe('hooks tests', () => {
expect(res.data!.amount).toBeGreaterThan(originalAmount)
})

// See https://github.com/reduxjs/redux-toolkit/issues/4267 - Memory leak in useQuery rapid query arg changes
test('Hook subscriptions are properly cleaned up when query is fulfilled/rejected', async () => {
const pokemonApi = createApi({
baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
endpoints: (builder) => ({
getTest: builder.query<string, number>({
async queryFn() {
await new Promise((resolve) => setTimeout(resolve, 1000));
return { data: "data!" };
},
keepUnusedDataFor: 0,
}),
}),
})

const storeRef = setupApiStore(pokemonApi, undefined, {
withoutTestLifecycles: true,
})

const checkNumQueries = (count: number) => {
const cacheEntries = Object.keys((storeRef.store.getState()).api.queries)
const queries = cacheEntries.length

expect(queries).toBe(count)
}

function User() {
const [fetchTest, { isFetching, isUninitialized }] =
pokemonApi.endpoints.getTest.useLazyQuery()

return (
<div>
<div data-testid="isUninitialized">{String(isUninitialized)}</div>
<div data-testid="isFetching">{String(isFetching)}</div>
<button data-testid="fetchButton" onClick={() => fetchTest(Math.random())}>
riqts marked this conversation as resolved.
Show resolved Hide resolved
fetchUser
</button>
</div>
)
}

render(<User />, { wrapper: storeRef.wrapper })
fireEvent.click(screen.getByTestId('fetchButton'))
fireEvent.click(screen.getByTestId('fetchButton'))
fireEvent.click(screen.getByTestId('fetchButton'))
riqts marked this conversation as resolved.
Show resolved Hide resolved

await act(async () => {
await delay(1000)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As that hasn't been defined in this file yet, you'll have to define it somewhere at the top of the file

  function delay(ms: number) {
    return new Promise((resolve) => setTimeout(resolve, ms))
  }

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe you should also just be able to re-use the delay function from msw:

import { delay } from 'msw'

await delay(1000)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My confusion here stems from the fact that it IS imported here and the test block directly below it uses it without problem.

Most likely I have just missed something painstakingly obvious, but I added a definition in the test block regardless.

})

// There should only be one stored query once they have had time to resolve
checkNumQueries( 1)
})

// See https://github.com/reduxjs/redux-toolkit/issues/3182
test('Hook subscriptions are properly cleaned up when changing skip back and forth', async () => {
const pokemonApi = createApi({
Expand Down