useRuntimeContext

Used to get the runtime context and can only be used in function components.

Usage

import { useRuntimeContext } from '@modern-js/runtime';

export function App() {
  const runtimeContext = useRuntimeContext();
  return <div>Hello World</div>;
}

Function Signature

type RuntimeContext = {
  request: {
    params: Record<string, string>;
    pathname: string;
    query: Record<string, string>;
    headers: IncomingHttpHeaders;
    cookie: string;
  };
  store: ReduckStore;
  router: RemixRouter;
};

function useRuntimeContext(): RuntimeContext;

Return Value

  • request: additional information in the request context.
    • params: dynamic parameters in the request path.
    • pathname: the pathname of the request.
    • query: the query of the request.
    • headers: the header info of the request.
    • cookie: the cookie of the request.
  • store: when the runtime.state is enabled, this value is the Reduck global store.
  • router: When the runtime.router is enabled, this value exists.
    • location: The current location reflected by the router. The same as [useLocation] the return value of (/apis/app/runtime/router/router.html#uselocation).
    • navigate: Navigate to the given path. The same as the return value of useNavigate.

Example

import { useRuntimeContext } from '@modern-js/runtime';
import { fooModel } from '@/common/models';

function App() {
  const { store } = useRuntimeContext();

  const [state, actions] = store.use(fooModel);

  return <div>state: {state}</div>;
}