Initial Query Data

· abundance's blog


There are many ways to supply initial data for a query to the cache before you need it:

Using initialData to prepopulate a query #

There may be times when you already have the initial data for a query available in your app and can simply provide it directly to your query. If and when this is the case, you can use the config.initialData option to set the initial data for a query and skip the initial loading state!

IMPORTANT: initialData is persisted to the cache, so it is not recommended to provide placeholder, partial or incomplete data to this option and instead use placeholderData

1const result = useQuery({
2  queryKey: ['todos'],
3  queryFn: () => fetch('/todos'),
4  initialData: initialTodos,
5})

staleTime and initialDataUpdatedAt #

By default, initialData is treated as totally fresh, as if it were just fetched. This also means that it will affect how it is interpreted by the staleTime option.

Initial Data Function #

If the process for accessing a query's initial data is intensive or just not something you want to perform on every render, you can pass a function as the initialData value. This function will be executed only once when the query is initialized, saving you precious memory and/or CPU:

1const result = useQuery({
2  queryKey: ['todos'],
3  queryFn: () => fetch('/todos'),
4  initialData: () => getExpensiveTodos(),
5})

Initial Data from Cache #

In some circumstances, you may be able to provide the initial data for a query from the cached result of another. A good example of this would be searching the cached data from a todos list query for an individual todo item, then using that as the initial data for your individual todo query:

1const result = useQuery({
2  queryKey: ['todo', todoId],
3  queryFn: () => fetch('/todos'),
4  initialData: () => {
5    // Use a todo from the 'todos' query as the initial data for this todo query
6    return queryClient.getQueryData(['todos'])?.find((d) => d.id === todoId)
7  },
8})

Initial Data from the cache with initialDataUpdatedAt #

Getting initial data from the cache means the source query you're using to look up the initial data from is likely old. Instead of using an artificial staleTime to keep your query from refetching immediately, it's suggested that you pass the source query's dataUpdatedAt to initialDataUpdatedAt. This provides the query instance with all the information it needs to determine if and when the query needs to be refetched, regardless of initial data being provided.

1const result = useQuery({
2  queryKey: ['todos', todoId],
3  queryFn: () => fetch(`/todos/${todoId}`),
4  initialData: () =>
5    queryClient.getQueryData(['todos'])?.find((d) => d.id === todoId),
6  initialDataUpdatedAt: () =>
7    queryClient.getQueryState(['todos'])?.dataUpdatedAt,
8})

Conditional Initial Data from Cache #

If the source query you're using to look up the initial data from is old, you may not want to use the cached data at all and just fetch from the server. To make this decision easier, you can use the queryClient.getQueryState method instead to get more information about the source query, including a state.dataUpdatedAt timestamp you can use to decide if the query is "fresh" enough for your needs:

 1const result = useQuery({
 2  queryKey: ['todo', todoId],
 3  queryFn: () => fetch(`/todos/${todoId}`),
 4  initialData: () => {
 5    // Get the query state
 6    const state = queryClient.getQueryState(['todos'])
 7
 8    // If the query exists and has data that is no older than 10 seconds...
 9    if (state && Date.now() - state.dataUpdatedAt <= 10 * 1000) {
10      // return the individual todo
11      return state.data.find((d) => d.id === todoId)
12    }
13
14    // Otherwise, return undefined and let it fetch from a hard loading state!
15  },
16})

Further reading #

For a comparison between Initial Data and Placeholder Data, have a look at the Community Resources.