useData()

Environment: server, client.
Implemented by: UI framework Vike extension vike-react/vike-vue/vike-solid (or yourself).

The useData() component hook allows you to access the value returned by the data() hook.

See Guides > Data Fetching for an introduction about useData() and fetching data in general.

You can also access the data over pageContext.data. In fact const { data } = usePageContext() returns the same value as useData().

Using pageContext.data instead of useData() makes sense if you want to access the data in Vike hooks since useData() only works inside UI components (not inside Vike hooks).

For example:

// SomeComponent.js
// Environment: server, client
 
import { useData } from 'vike-react/useData' // or vike-vue / vike-solid
 
  // Inside a React/Vue/Solid component
  const data = useData()
  const { name, price } = data
// /pages/product/@id/+data.js
// Environment: server
 
export { data }
 
async function data(pageContext) {
  let product = await Product.findById(pagContext.routeParams.id)
 
  // `product` is serialized and passed to the client. Therefore, we pick only the
  // data the client needs in order to minimize what is sent over the network.
  product = { name: product.name, price: product.price }
 
  return product
}

See Guides > Data Fetching for more information about data fetching.

TypeScript

// /pages/product/SomeComponent.ts
// Environment: server, client
 
import type { Data } from './+data'
 
  // Inside a React/Vue/Solid component
  const data = useData<Data>()
// /pages/product/+data.ts
// Environment: server
 
export { data }
export type Data = Awaited<ReturnType<typeof data>>
 
import type { PageContextServer } from 'vike/types'
 
async function data(pageContext: PageContextServer) {
  // ...
}

Using type inference as shown above is usually what you want, but if you want to enforce a type instead:

// +data.ts
 
export { data }
export type { Data }
 
type Data = /* the type you want to enforce */
 
import type { DataAsync } from 'vike/types'
 
const data: DataAsync = async (pageContext): Promise<Data> => {
  // ...
}

Without vike-{react,vue,solid}

In case you don't use a UI framework Vike extension vike-react/vike-vue/vike-solid, you can implement useData() yourself.

In general, for improved DX, we recommend using a useData() implementation. But you don't have to as shown at API > data() hook > Without vike-{react,vue,solid}.

Examples:

See also