useData()

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

The useData() component hook allows you to access the data that is returned by a data() hook.

// SomeComponent.js
// Environment: server, client

import { useData } from 'vike-react/useData'
/* Or:
import { useData } from 'vike-vue/useData'
import { useData } from 'vike-solid/useData'
*/

  // Inside a UI 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.

Examples

See API > data() hook > Examples.

TypeScript

// /pages/product/SomeComponent.ts
// Environment: server, client

import type { Data } from './+data'

  // Inside a UI 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 extension

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 useData().

Examples:

See also