query icon indicating copy to clipboard operation
query copied to clipboard

Unnecessary re-render with enabled false

Open burakgormek opened this issue 1 year ago • 6 comments

Describe the bug

Nested useQuery with the same queryKey and parent is enabled: false triggers unnecessary re-render. It will not trigger re-rendering if parent is set to enabled: true.

Your minimal, reproducible example

https://codesandbox.io/p/devbox/happy-hoover-q9xmlw

Steps to reproduce

  1. Go to the codesandbox link
  2. See sandbox console to look renders

Expected behavior

Not trigger re-render, same as if parent is enabled.

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

MacOS - Chrome 121.0.6167.85

Tanstack Query adapter

react-query

TanStack Query version

v5.17.22

TypeScript version

No response

Additional context

No response

burakgormek avatar Jan 30 '24 12:01 burakgormek

I think when both are enabled, the parent initiates the fetching. Now, the child initiates the fetching and it kinda depends on our batching if there is going to be another re-render or not. You can adapt batching functionality here:

https://tanstack.com/query/v5/docs/reference/notifyManager#notifymanagersetscheduler

TkDodo avatar Jan 30 '24 12:01 TkDodo

Thanks for the fast response. I see, for enabled scenario, that makes sense but...

Doesn't the parent have to do nothing if it's not enabled? Although nothing is changed in destructed values. (isError just an example)

burakgormek avatar Jan 30 '24 12:01 burakgormek

yeah there's something "off" here since isError didn't change, there shouldn't be a re-render for this observer. Would you like to look into it ?

TkDodo avatar Jan 30 '24 13:01 TkDodo

I did a little look to find what cause a re-render but not found anything yet. Its not easy to understand the internals for the first look (for me).

I want to look deeper into it, but our project deadline does not allow it :/

burakgormek avatar Jan 30 '24 15:01 burakgormek

Try to pass enabled prop to the child component,

  1. In Parent Component pass the enabled prop down to the child component enabled={isError}

2)In Child Component enabled: enabled, // Set enabled based on the parent's status

ensuring that the child's useQuery hook represents the parent's enabled status

Mrityunjay-Palled avatar Feb 11 '24 16:02 Mrityunjay-Palled