<!-- WARNING: keep links absolute in this file so they work on NPM too -->

vike-react-queryEnables your SSR React components to fetch data using TanStack Query.
Powered by react-streaming.
Features:
- Data is fetched at the component level (unlike +data, which fetches at the page level)
- The rest of the page is eagerly rendered while the component waits for its data (see Progressive Rendering)
- All TanStack Query niceties
- All SSR benefits
- Fallback upon loading and/or error
- Caching
You can completely stop using Vike's +data hook — or use both: +data for some pages, and vike-react-query for others.
> [!NOTE]
> If you don't use SSR (i.e. SPA/SSG with pre-rendering), then you don't need vike-react-query — you can use TanStack Query without any Vike integration.
Table of Contents
Installation
Basic usage
Example withFallback() tags
Error Handling
Settings
Usage with Telefunc
Version history
How it works
See also
1. npm install @tanstack/react-query vike-react-query
2. Extend +config.js:
``js
// pages/+config.js
import vikeReact from 'vike-react/config'
import vikeReactQuery from 'vike-react-query/config'
export default {
// ...
extends: [vikeReact, vikeReactQuery]
}
`
> [!NOTE]
> The vike-react-query extension requires vike-react.
`jsx
import { useSuspenseQuery } from '@tanstack/react-query'
const Movie = ({ id }) => {
const result = useSuspenseQuery({
queryKey: ['movie', id],
queryFn: () =>
fetch(https://brillout.github.io/star-wars/api/films/${id}.json)
.then((res) => res.json())
})
const { title } = result.data
return (
useSuspenseQuery() is imported from @tanstack/react-query, you need to install vike-react-query for it to work. (The useSuspenseQuery() hook requires an HTML stream integration.)
Example
See examples/query/.
withFallback()`js
withFallback(Component) // Use default loading fallback (see +Loading)
withFallback(Component, Loading) // Define loading fallback
withFallback(Component, Loading, Error) // Define loading and error fallback
withFallback(Component, undefined, Error) // Define error fallback
``tsx
// Movie.tsximport { useSuspenseQuery } from '@tanstack/react-query'
import { withFallback } from 'vike-react-query'
const Movie = withFallback(
({ id }: { id: string }) => {
const result = useSuspenseQuery({
queryKey: ['movie', id],
queryFn: () =>
fetch(
https://brillout.github.io/star-wars/api/films/${id}.json)
.then((res) => res.json())
}) const { title } = result.data
return (
Title: {title}
)
},
({ id }) => Loading movie {id},
// The props retry and error are provided by vike-react-query
// Other props, such as code, are provied by the parent component
({ id, retry, error }) => (
Failed to load movie {id}
)
)
`
+LoadingIf you skip the
Loading parameter, then a default loading component (provided by vike-react) is used. You can create a custom default loading component:`jsx
// pages/+Loading.jsxexport default { component: LoadingComponent }
function LoadingComponent() {
// Applies on a component-level
return
Loading...
}
`Instead of adding a loading fallback to the component, you can set a loading fallback to the page and layouts:
`jsx
// pages/+Loading.jsxexport default { layout: LoadingLayout }
function LoadingLayout() {
// Applies to the page and all layouts
return
Loading...
}
`> [!NOTE]
> The
+Loading.layout setting is optional and only relevant when using useSuspenseQuery() without withFallback() or withFallback(Component, false).
> `js
> withFallback(Component, false) // Don't set any loading fallback
> withFallback(Component, undefined) // Use default loading fallback
> `Manual
boundaryTechnically speaking:
-
withFallback() wraps the component inside a boundary.
- +Loading.layout adds a boundary to the component as well as to all components.You can also manually add a
boundary at any arbitrary position:`js
import { Suspense } from 'react'function SomePageSection() {
return (
Loading...
tagsTo set tags such as
and based on fetched data, you can use useConfig() / / .`js
import { useSuspenseQuery } from '@tanstack/react-query'
import { Config } from 'vike-react/Config'
import { Head } from 'vike-react/Head'function Movies() {
const query = useSuspenseQuery({
queryKey: ['movies'],
queryFn: () => fetch('https://star-wars.brillout.com/api/films.json')
})
const movies = query.data
return (
${movies.length} Star Wars Movies} />
All ${movies.length} movies from the Star Wars franchise.} />
{
movies.map(({ title }) => (
- {title}
))
}
)
}
`
> [!NOTE]
> The
tag is only shown to bots. See the explanation at Vike Docs > useConfig > HTML Streaming.
Error Handling
From a UI perspective, the classic approach to handling errors is the following.
- Show a 404 page, for example
This page could not found.
.
- Show an error page, for example Something went wrong.
.
- Redirect the user, for example redirecting the user to /publish-movie upon /movie/some-fake-movie-title because there isn't any movie some-fake-movie-title.But because
vike-react-query leverages HTML streaming these approaches don't work (well) and we recommend the following instead.
- Show a not-found component, for example No movie some-fake-movie-title found.
.
- Show an error component, for example Something went wrong (couldn't fetch movie), please try again later.
.
- Show a link (instead of redirecting the user), for example No movie some-fake-movie-title found. You can publish a new movie.
.withFallback()> [!NOTE]
> HTML chunks that are already streamed to the user cannot be reverted and that's why page-level redirection (
throw redirect) and rewrite (throw render()) don't work (well).
>
> Also it isn't idiomatic: the whole idea of collocating data-fetching with the UI component is to think in terms of the component in isolation rather than in terms of the page.
Settings
QueryClient.`js
// +config.jsexport default {
queryClientConfig: {
defaultOptions: {
queries: {
staleTime: 60 * 1000
}
}
}
}
`pageContext:`js
// +queryClientConfig.jsexport default (pageContext) => ({
defaultOptions: {
queries: {
staleTime: pageContext.data.staleTime,
retry: pageContext.routeParams.userId ? true : false
}
}
})
`> [!NOTE]
> You can apply settings to all pages, a group of pages, or only one page. See Vike Docs > Config > Inheritance.
Usage with Telefunc
You can use
vike-react-query with Telefunc.> [!NOTE]
> By using
vike-react-query with Telefunc, you combine RPC with all TanStack Query features.With Telefunc, the query function always runs on the server.
Query example
`tsx
// movie.telefunc.tsexport async function getMovie(id: string) {
const movie = await prisma.movie.findUnique({ where: id })
return movie;
}
`
`tsx
// movie.tsximport { useSuspenseQuery } from '@tanstack/react-query'
import { withFallback } from 'vike-react-query'
import { getMovie } from './movie.telefunc'
const Movie = withFallback(
({ id }: { id: string }) => {
const query = useSuspenseQuery({
queryKey: ['movie', id],
queryFn: () => getMovie(id)
})
const { title } = query.data
return (
Title: {title}
)
},
({ id }) => Loading movie {id},
({ id, retry }) => (
Failed to load movie {id}
)
)
`Mutation example
`tsx
// movie.telefunc.tsexport async function createMovie({ title }: { title: string }) {
const movie = await prisma.movie.create({ data: { title } })
return movie
}
`
`tsx
// movie.tsximport { useMutation } from '@tanstack/react-query'
import { createMovie } from './movie.telefunc'
const CreateMovie = () => {
const ref = useRef(null)
const mutation = useMutation({
mutationFn: createMovie
})
const onCreate = () => {
const title = ref.current?.value || 'No title'
mutation.mutate({ title })
}
return (
{mutation.isPending && 'Creating movie..'}
{mutation.isSuccess && 'Created movie ' + mutation.data.title}
{mutation.isError && 'Error while creating the movie'}
)
}
`Putting it together
`tsx
// movie.telefunc.tsexport async function getMovies() {
const movies = await prisma.movie.findMany()
return movies;
}
export async function createMovie({ title }: { title: string }) {
const movie = await prisma.movie.create({ data: { title } })
return movie
}
`
`tsx
// movie.tsximport { useSuspenseQuery, useMutation } from '@tanstack/react-query'
import { withFallback } from 'vike-react-query'
import { getMovies, createMovie } from './movie.telefunc'
const Movies = withFallback(
() => {
const queryClient = useQueryClient()
const query = useSuspenseQuery({
queryKey: ['movies'],
queryFn: () => getMovies()
})
const mutation = useMutation({
mutationFn: createMovie,
onSuccess() {
query.invalidateQueries({ queryKey: ['movies'] })
// or query.refetch()
}
})
const ref = useRef(null)
const onCreate = () => {
const title = ref.current?.value || 'No title'
mutation.mutate({ title })
}
return (
{query.data.map((movie) => (
Title: {movie.title}
))}
{mutation.isPending && 'Creating movie..'}
{mutation.isSuccess && 'Created movie' + mutation.data.title}
{mutation.isError && 'Error while creating the movie'}
)
},
Loading movies,
({ retry }) => (
Error while loading movies
)
)
`
Version history
See CHANGELOG.md.
How it works
On the server side (during SSR), the component is rendered to HTML and its data is loaded. On the client side, the component is just hydrated: the data fetched on the server is passed to the client and reused.
Upon page navigation (and rendering the first page if SSR is disabled), the component is rendered and its data loaded on the client-side.
> [!NOTE]
> Behind the scenes
vike-react-query integrates TanStack Query into react-streaming.
See also
- Vike Docs > TanStack Query
- Vike Docs > Data Fetching
- TanStack Query > useSuspenseQuery
- React >