Capítulo 24 de 80
initialData seeds the cache with real data and skips the initial loading state entirely — unlike placeholderData, it persists to the cache, so it must be treated as trustworthy data, not a partial/fake preview (that's what placeholder data is for).
initialData on the query itself; imperatively via prefetching (queryClient.query) or a direct queryClient.setQueryData write.staleTime: initialData is treated as freshly-fetched by default, so with the default staleTime: 0 the query shows the initial data immediately and immediately refetches on mount; with a positive staleTime, the data is considered fresh for that window before any refetch.initialDataUpdatedAt: the accurate way to represent initial data that isn't actually fresh — pass the real timestamp (ms) it was captured at, and let staleTime do its normal freshness math against that real age instead of pretending the data was just fetched.queryClient.getQueryData(['todos'])?.find(...)) as initialData for an individual-item query — pair this with initialDataUpdatedAt: () => queryClient.getQueryState(['todos'])?.dataUpdatedAt so staleness is computed against the source query's real age, not assumed to be "just fetched."queryClient.getQueryState(['todos'])?.dataUpdatedAt against a freshness threshold before deciding to use it at all — return undefined to fall back to a normal hard loading fetch instead.// Naive: initialData treated as fresh right now (refetches immediately with staleTime: 0)
useQuery({ queryKey: ['todos'], queryFn: () => fetch('/todos'), initialData: initialTodos })
// Accurate: initialData's real age is known, staleTime governs it correctly
useQuery({
queryKey: ['todos', todoId],
queryFn: () => fetch(`/todos/${todoId}`),
initialData: () => queryClient.getQueryData(['todos'])?.find((d) => d.id === todoId),
initialDataUpdatedAt: () => queryClient.getQueryState(['todos'])?.dataUpdatedAt,
})
staleTime decides refetching correctly.initialData is persisted to the cache — never pass partial/fake/placeholder-shaped data here, that's exactly what placeholderData (Chapter 25) is for.initialDataUpdatedAt sourced from that query's real dataUpdatedAt — otherwise you're lying to staleTime about how fresh the data is.initialData whenever computing it isn't free — it runs exactly once per query initialization.staleTime governs refetch timing, which initialDataUpdatedAt feeds into accurately.