getPageContext()
The getPageContext()
function allows you to access the pageContext
object inside Vike hooks.
It's only useful if you're building a Vike extension and you want to implement a universal hook. If you aren't building a Vike extension, then you don't need to know about
getPageContext()
.
For example:
// /pages/some-page/+data.js
export { data }
import { getPageContext } from 'vike/getPageContext'
function data() {
const pageContext = getPageContext()
// ...
}
It's the same object than the function data(pageContext)
argument and the following is equivalent:
// /pages/some-page/+data.js
export { data }
import { getPageContext } from 'vike/getPageContext'
function data() {
const pageContext = getPageContext()
function data(pageContext) {
// ...
}
You may ask yourself what the purpose of getPageContext()
is and, indeed, it's useless for Vike users. But, if you are implementing a Vike extension and you want to implement a universal hook, then getPageContext()
is useful, see Example.
Universal Hooks
A universal hook is a component hook that also works inside Vike hooks such as API > useConfig()
.
// /components/SomeReactComponent.jsx
import { useConfig } from 'vike-react/useConfig' // or vike-{vue,solid}
function SomeReactComponent() {
// Not only can useConfig() be used inside a component...
const document = useConfig()
}
// /pages/some-page/+data.js
import { useConfig } from 'vike-react/useConfig'
export function data() {
// ... but it can also be used inside a Vike hook.
const document = useConfig()
}
Example
In order to make useConfig()
a universal hook (see Universal Hooks), the useConfig()
implementation uses getPageContext()
:
// node_modules/vike-{react,vue,solid}/dist/hooks/useConfig.js
import { usePageContext } from './usePageContext'
import { getPageContext } from 'vike/getPageContext'
export function useConfig() {
// useConfig() needs to access the pageContext object
// In case useConfig() is used inside a Vike hook
let pageContext = getPageContext()
// In case useConfig() is used inside a React component
if (!pageContext) {
pageContext = usePageContext()
}
// ...
}