Runtime API

Rspress exposes some runtime APIs, which is convenient for you to do some custom logic.

usePageData

  • Type: () => PageData

Get the data of the current page, and the return value is an object, which contains all the data of the current page.

import { usePageData } from 'rspress/runtime';

function MyComponent() {
  const pageData = usePageData();
  return <div>{pageData.page.title}</div>;
}

useLang

  • Type: () => string

Get the current language, the return value is a string, which is the current language.

import { useLang } from 'rspress/runtime';

function MyComponent() {
  const lang = useLang();
  // lang === 'zh-CN'
  return <div>{lang}</div>;
}

useVersion

  • Type: () => string

Get the current version, the return value is a string, which is the current version.

import { useVersion } from 'rspress/runtime';

export default () => {
  const version = useVersion();
  return <div>Current version: {version}</div>;
};

useDark

  • Type: () => boolean

Whether it is dark mode currently, the return value is a boolean value.

import { useDark } from 'rspress/runtime';

function MyComponent() {
  const dark = useDark();
  return <div>{dark}</div>;
}

Note that in the SSG process, useDark cannot accurately reflect the theme setting of the user's browser, because SSG is executed during the build stage. Only after client hydration is complete, this hook will return the correct theme value.

If you need to apply a dark theme style in the SSG stage, it is recommended to use the CSS selector .dark to set the style. Rspress will add the dark class name to the root element of the document, which will be effective in both SSG and client:

/* Light mode style */
.my-component {
  color: black;
  background-color: white;
}

/* Dark mode style */
.dark .my-component {
  color: white;
  background-color: #1a1a1a;
}

useI18n

The framework provides useI18n this hook to get the internationalized text, the usage is as follows:

import { useI18n } from 'rspress/runtime';

const MyComponent = () => {
  const t = useI18n();

  return <div>{t('gettingStarted')}</div>;
};

For better type hinting, you can configure paths in tsconfig.json:

{
  "compilerOptions": {
    "paths": {
      "i18n": ["./i18n.json"]
    }
  }
}

Then use it like this in the component:

import { useI18n } from 'rspress/runtime';

const MyComponent = () => {
  const t = useI18n<typeof import('i18n')>();

  return <div>{t('gettingStarted')}</div>;
};

This way you get type hints for all literal keys defined in i18n.json.

See more in Internationalization.

Router hook

Rspress internally uses and re-exports all APIs of react-router-dom, you can use it like this:

import { useLocation } from 'rspress/runtime';

function MyComponent() {
  const location = useLocation();
  return <div>{location.pathname}</div>;
}