useRuntimeContext

This function is primarily used to obtain the runtime context and can only be used in the function component.

Usage

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

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

Function Signature

type RuntimeContext = {
  context: RequestContext;
};

context

Used to get Request Context.

Example

Distinguish the runtime environment

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

  if (context.isBrowser === true) {
    // browser-side execution logic
    console.log('browser render')
  } else {
    // The server-side executes logic, which can access the unique 'logger' attribute
    context.logger.info('server render')
  }
}

Request context

When SSR is enabled, uniform request contexts can be obtained in both the node environment and the browser-side environment.

The slightly different is that the node environment also supports setting response headers, response codes, and provides Logger logs and Metrics management.

TIP

when ssr is disabled, only the part of information that can be obtained in the browser environment is included.

RequestContext
ServerContext
ClientContext
type RequestContext = ServerContext | ClientContext;