Skip to content

[docs] Confusion about Caching and Staleness #1082

@TkDodo

Description

@TkDodo

Describe the bug

In the important defaults section, it says:

Query results that are currently rendered on the screen (via useQuery and similar hooks) will become "stale" immediately after they are resolved and will be refetched automatically in the background when they are rendered or used again.

To me, this sounds like whenever we re-render a component (for whatever reason) that has a useQuery hook, it will do a re-fetch. But that is clearly not the case. I have amended the simple example from the docs a bit:

https://codesandbox.io/s/sad-dewdney-rz197

There are two buttons that just force a re-render via Math.random. Clicking them will not trigger a refetch, even though the data is stale. I think this is fine and intended, it's just that the passage in the docs states differently (or am I just interpreting it wrongly?)

The caching docs state this a bit better I believe:

Stale queries are automatically refetched whenever their query keys change (this includes variables used in query key tuples), when they are freshly mounted from not having any instances on the page, or when they are refetched via the query cache manually.

This should be the source of truth, so maybe we should just remove the sentence from the important defaults section and link to the caching guide?

I've also found articles our there that claim that react-query re-fetches on every re-render, like this one:

Rendered query results will become stale after they are resolved. This means that they will be refetched automatically on every rerender. To avoid this, we should specify the staleTime property.

So maybe I'm not the only one who is confused 😅


The detailed caching example also has a minor confusion point in it:

A second instance of useQuery('todos', fetchTodos) mounts elsewhere.
Because this exact data exist in the cache from the first instance of this query, that data is immediately returned from the cache.

Yes, the data will be returned from the cache, but also, a background re-fetch will happen, unless you set refetchOnMount to false. I think this is worth mentioning.

Expected behavior

The docs should be clear and understandable and one section should not contradict the other :)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions