Framework
Version

Caching Examples

Bitte lesen Sie die wichtigen Standardeinstellungen sorgfältig durch, bevor Sie diesen Leitfaden lesen.

Basic Example

This caching example illustrates the story and lifecycle of

  • Query Instances with and without cache data
  • Background Refetching
  • Inactive Queries
  • Garbage Collection

Let's assume we are using the default gcTime of 5 minutes and the default staleTime of 0.

  • Eine neue Instanz von injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos })) wird initialisiert.
    • Since no other queries have been made with the ['todos'] query key, this query will show a hard loading state and make a network request to fetch the data.
    • When the network request has completed, the returned data will be cached under the ['todos'] key.
    • Das Datum wird nach der konfigurierten staleTime (Standard ist 0, also sofort) als veraltet markiert.
  • Eine zweite Instanz von injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos }) wird woanders initialisiert.
    • Since the cache already has data for the ['todos'] key from the first query, that data is immediately returned from the cache.
    • The new instance triggers a new network request using its query function.
      • Beachten Sie, dass unabhängig davon, ob beide fetchTodos Query-Funktionen identisch sind oder nicht, die Status beider Queries aktualisiert werden (einschließlich isFetching, isPending und anderer verwandter Werte), da sie denselben Query-Schlüssel haben.
    • When the request completes successfully, the cache's data under the ['todos'] key is updated with the new data, and both instances are updated with the new data.
  • Beide Instanzen der injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos }) Query werden zerstört und sind nicht mehr in Gebrauch.
    • Since there are no more active instances of this query, a garbage collection timeout is set using gcTime to delete and garbage collect the query (defaults to 5 minutes).
  • Bevor der Cache-Timeout abgelaufen ist, wird eine weitere Instanz von injectQuery(() => ({ queryKey: ['todos'], queyFn: fetchTodos }) eingebunden. Die Query gibt sofort die verfügbaren gecachten Daten zurück, während die fetchTodos Funktion im Hintergrund ausgeführt wird. Wenn sie erfolgreich abgeschlossen ist, wird der Cache mit frischen Daten gefüllt.
  • Die letzte Instanz von injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos }) wird zerstört.
  • Es erscheinen keine weiteren Instanzen von injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos }) innerhalb von 5 Minuten.
    • The cached data under the ['todos'] key is deleted and garbage collected.

Für weiter fortgeschrittene Anwendungsfälle siehe injectQuery.