A cache temporarily stores previously fetched data so components can reuse it immediately instead of waiting for the server again. In React Query, a query key identifies cached data; the library can return that data first, then fetch a newer version in the background. section 10.3.1 section 10.3.3
A query cache supports responsive server-state workflows by:
- Reusing data across components that call useQuery with the same key, avoiding repeated loading states. section 10.3.3
- Deduplicating requests for the same data and fetching out-of-date data in the background. section 10.3.1
- Representing parameterized data with serializable keys such as ["bookings", bookableId, start, end]. section 10.3.3
- Providing direct access through useQueryClient and getQueryData when a component needs existing cached data. section 10.3.4
Prefilling an edit form from cached data
After the Bookables page has loaded the full list, BookableEdit can obtain the query client, read getQueryData("bookables"), find the requested ID, and pass that result as initialData. The edit form can therefore display existing details immediately while useQuery manages the individual bookable query. section 10.3.4
Listing 10.13 The BookableEdit component accessing the cache
import {useParams} from "react-router-dom";
import {useQueryClient, useQuery} from "react-query"; #1
import useFormState from "./useFormState";
import getData from "../../utils/api";
import BookableForm from "./BookableForm";
import PageSpinner from "../UI/PageSpinner";
export default function BookableEdit () {
const {id} = useParams();
const queryClient = useQueryClient(); #2
const {data, isLoading} = useQuery( #3
["bookable", id],
() => getData(`http://localhost:3001/bookables/${id}`),
{
initialData: #4
queryClient.getQueryData("bookables") #5
?.find(b => b.id === parseInt(id, 10)) #6
}
);
const formState = useFormState(data); #7
function handleDelete() {}
function handleSubmit() {}
if (isLoading) { #8
return <PageSpinner/>
}
return (
<BookableForm
formState={formState}
handleSubmit={handleSubmit}
handleDelete={handleDelete}
/>
);
}
#1 Import the useQueryClient hook.
#2 Call the hook and assign the client to a variable.
#3 Assign the initial data and subsequent fetched data to the data variable.
#4 Use the initialData property to assign an initial value to data.
#5 Use a key to get specific data from the cache.
#6 Find the bookable for the specified ID.
#7 Set the bookable data as the state for the form.
#8 Use the isLoading Boolean returned by useQuery.
Inspect the complete BookableEdit example, including useQueryClient, getQueryData, the individual query key, and initialData. section 10.3.4





































