usePageContext()

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

The usePageContext() hook enables any UI component to access the pageContext object.

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

  // Inside a UI component
  const pageContext = usePageContext()

Without Vike extension

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

React

You can use React Context to make pageContext accessible from any React component.

Examples:

Vue 3 - Composition API

You can use app.provide() with inject() to make pageContext accessible from any Vue component.

// app.js

const app = createSSRApp(/*...*/)
app.provide('pageContext', pageContext)
<!-- someComponent.vue -->

<template>
  <!-- We can access `pageContext` here -->
  {{ pageContext.someProp }}
</template>

<script setup>
import { inject } from 'vue'
const pageContext = inject('pageContext')
</script>

You can also implement a usePageContext() component hook:

// usePageContext.js

import { inject } from 'vue'

export { usePageContext }
export { setPageContext }

const key = Symbol()

function usePageContext() {
  const pageContext = inject(key)
  return pageContext
}
function setPageContext(app, pageContext) {
  app.provide(key, pageContext)
}
const app = createSSRApp(/*...*/)
setPageContext(app, pageContext)
<script setup>
import { usePageContext } from './path/to/usePageContext'
const pageContext = usePageContext()
</script>

Examples:

Vue 3 - globalProperties

Alternatively, you can make pageContext available to all Vue components by using app.config.globalProperties.

// app.js

const app = createSSRApp(/*...*/)
app.config.globalProperties.$pageContext = pageContext
<!-- someComponent.vue -->

<template>
  <!-- We can access `pageContext` here -->
  {{ $pageContext.someProp }}
</template>

<script setup>
import { getCurrentInstance } from 'vue'
// We can access `pageContext` here
const pageContext = getCurrentInstance().appContext.config.globalProperties.$pageContext
</script>

Example:

Vue 2

For Vue 2 you can use Vue.prototype.

See also