reactjsreact-querytanstackreact-query

What is the difference between the 'initialData' and 'placeholderData' options in the React Query v5 useQuery hook?


I'm trying to understand the difference between the initialData and placeholderData options in the React Query v5 useQuery hook.

I'm unclear on when to use each of these options. What are the specific scenarios or use cases where initialData or placeholderData would be more appropriate?

If someone could clarify the distinction and provide some practical examples, that would be great!


Solution

  • I have written a full blog post on the differences between the two:

    https://tkdodo.eu/blog/placeholder-and-initial-data-in-react-query

    In short, initialData goes straight to the cache, while placeholderData is something that is only returned for the component instance using it (the "Observer" created by useQuery). placeholderData is not real, so the Query will behave as if it were in pending state (because it is), but for your component, it will look like a success state in the meantime. That influences how refetches are done, and what happens to that data if the query goes into error state.