Skip to content

useContext

reference
1 min readUpdated

Kind: Function

Source: src/jsx/context.ts

Part of: Jsx

Read the current value of a context created with createContext.

Safe to call from async components after await. See createContext for the per-runtime isolation guarantees.

useContext reads the current value from a context created with createContext. It can be called in synchronous or asynchronous components, including after an await, while keeping context values isolated per runtime.

Signature

ts
function useContext(context: Context<T>): T

Parameters

NameType
contextContext<T>

Returns: T

Diagram

mermaid
graph LR
  A[createContext] --> B[Context]
  B --> C[Context.Provider]
  C --> D[Component]
  D --> E[useContext]
  E --> F[Current context value]

Usage

tsx
import { createContext, useContext } from 'hono/jsx'

const ThemeContext = createContext('light')

const ThemeLabel = async () => {
  await Promise.resolve()

  const theme = useContext(ThemeContext)

  return <span>Theme: {theme}</span>
}

const App = () => (
  <ThemeContext.Provider value="dark">
    <ThemeLabel />
  </ThemeContext.Provider>
)

AI Coding Instructions

  • Create contexts with createContext before reading them with useContext.
  • Pass the context object returned by createContext directly to useContext.
  • Read context inside a component that is rendered below the matching Context.Provider.
  • useContext may run after await in an async component.

Used by

7 references from 7 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example.

Imported by (7)

  • Propssrc/jsx/base.ts:27
  • childrenToStringsrc/jsx/components.ts:14
  • FormContextsrc/jsx/dom/hooks/index.ts:24
  • clearCachesrc/jsx/dom/intrinsic-element/components.ts:18
  • HasRenderToDomsrc/jsx/dom/render.ts:30
  • titlesrc/jsx/intrinsic-element/components.ts:121
  • StreamingContextsrc/jsx/streaming.ts:30

Was this page helpful?

Download as PDF
useContext — Hono (narrator proof)