# useRuntimeContext

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

## Usage

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

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

## Function Signature

```ts
type RuntimeContext = {
  context: RequestContext;
};
```

### context

Used to get [Request Context](#request-context).

## Example

### Distinguish the runtime environment

```ts
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.

:::

import { Tabs, Tab as TabItem } from "@theme";

<Tabs
  defaultValue="RequestContext"
  values={[
    { label: 'RequestContext', value: 'RequestContext', },
    { label: 'ServerContext', value: 'ServerContext', },
    { label: 'ClientContext', value: 'ClientContext', },
  ]
}>
<TabItem value="RequestContext">

```ts
type RequestContext = ServerContext | ClientContext;
```

</TabItem>
<TabItem value="ServerContext">

```ts
interface ServerContext {
  isBrowser: false;
  request: {
    userAgent: string;
    cookie: string;
    cookieMap: Record<string, any>;
    query: Record<string, any>;
    url: string;
    host: string;
    headers?: IncomingHttpHeaders;
  };
  response: {
    setHeader: (key: string, value: string) => void;
    status: (code: number) => void;
  }
  logger: Logger;
  metrics: Metrics;
}
```

</TabItem>
<TabItem value="ClientContext">

```ts
interface ClientContext {
  isBrowser: true;
  request: {
    userAgent: string;
    cookie: string;
    cookieMap: Record<string, any>;
    query: Record<string, any>;
    url: string;
    host: string;
    headers?: IncomingHttpHeaders;
  };
}
```

</TabItem>
</Tabs>
