Skip to content

Unexpected refetch when changing query key (data for new query key is already cached) #4444

@emillundstrm

Description

@emillundstrm

Describe the bug

When mounting a new component that uses useQuery, you can set the remountOnFetch option to false to avoid an unnecessary fetch.

If you instead update the query of an already mounted component, there is (as far as I can tell?) no way to avoid a fetch, even if the new query key already has data in the cache.

So if you force React to recreate the component (via the key prop) you can avoid the refetch, but if you reuse the same component, you cannot. I had hoped there was a way to avoid the refetch without forcing a remount.

Your minimal, reproducible example

https://codesandbox.io/s/awesome-breeze-jdvq9o?file=/src/index.jsx

Steps to reproduce

  1. Click button labeled "2"
  2. Click button labeled "1"
  3. Click button labeled "2" again
  4. Note that during step 2 and step 3, queries ["testQuery", 1] and ["testQuery", 2] are refetched, but ["testQuery", 3] and ["testQuery", 4] are not.

Expected behavior

Since I have refetchOnMount set to false, I expect no refetch after clicking the button a second time. I expect it to use the data from the cache.

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

Chrome, Linux

react-query version

4.14.1

TypeScript version

No response

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions