Skip to content
Source
Sign inSign up
TanStack/query

Infinite re-renders when using `select` in `useInfiniteQuery` #3068

Send to my agent
Closedcarljohnson93(GitHub profile, opens in a new tab) opened this issue 7 comments

Describe the bug When I transform data from infinite query with select option, I get infinite re-renders in my component

To Reproduce Add following component and render it (implied that it'll be wrapped in QueryClientProvider of course):

import { useInfiniteQuery } from 'react-query';
import { nanoid } from 'nanoid';

const App = () => {
  const query = useInfiniteQuery(
    'todos',
    ({ pageParam = 0 }) => fetchTodo(pageParam),
    {
      getNextPageParam: ({ nextCursor }) => nextCursor,
      select: ({ pages, pageParams }) => ({
        pages: pages.map(({ todos }) => (
          todos.map(todo => ({
            ...todo,
            localId: nanoid(),
          }))
        )),
        pageParams: [...pageParams],
      })
    },
  );

  console.log('re-render')

  return null;
};

const todos = [];

for (let i = 0; i < 100; i++) {
  todos.push({ id: nanoid(), text: `Todo ${i + 1}` });
}

const TODOS_FETCH_PORTION = 10;

const fetchTodo = (cursor) => {
  const nextCursor = cursor + TODOS_FETCH_PORTION;
  const result = {
    todos: todos.slice(cursor, nextCursor),
  };
  if (todos.length - 1 >= nextCursor) {
    result.nextCursor = nextCursor;
  }
  return result;
};

export default App;

Expected behavior Expected App to not re-render infinitely.

Desktop (please complete the following information):

  • OS: macOS 10.13.6
  • Browser: Chrome 96.04

Additional info With useQuery this bug does not occur

  1. can you please provide a codesandbox reproduction, thanks.

  2. TkDodo added labelsbug

  3. thanks, I think I found the issue. infiniteQueryObserver overwrites setOptions of queryObserver, but doesn't forward the second parameter (notifyOptions):

    https://github.com/tannerlinsley/react-query/blob/b84681fdc7d37645cd149f40e98cb18fd8bc393c/src/core/infiniteQueryObserver.ts#L64-L76

    what we would need is this to match the parent signature.

      setOptions(
        options?: InfiniteQueryObserverOptions<
          TQueryFnData,
          TError,
          TData,
          TQueryData
        >,
        notifyOptions?: NotifyOptions
      ): void {
        super.setOptions(
          {
            ...options,
            behavior: infiniteQueryBehavior(),
          },
          notifyOptions
        )
      }

    the missing notifyOptions will lead to the select result being calculated twice, which in your case is fatal because nanoid() will return a new value every time.

    would you maybe like to contribute that change?

    btw - if select is an inline function, it will still run on every render, so also on useQuery, the id is generated on every render. If you expect it to be stable, you'd have to make sure select itself is memoized (or do the transformation inside the queryFn).

  4. Forwarding notifyOptions didn't help. I was able to fix this bug by moving local id generation to the queryFn. Didn't know select is called every render. Thank you!

  5. Interesting. Let me keep this issue open because I still think it’s a bug in RQ. I can try to create a test case from your sandbox and take it from there :)

  6. TkDodo reopened this

  7. TkDodo closed this

  8. :tada: This issue has been resolved in version 3.34.2 :tada:

    The release is available on:

    Your semantic-release bot :package::rocket:

  9. tannerlinsley added labelsreleased

  10. :tada: This issue has been resolved in version 4.0.0-alpha.2 :tada:

    The release is available on:

    Your semantic-release bot :package::rocket:

  11. tannerlinsley added labelsreleased on @alpha

Sign in to join this conversation.