Skip to content
Vincle
Esc

Loading…

    Context & Scope

    Vincle has two ways to share values. Tree Context passes a value to descendants of a JSX Provider. Scope holds mutable state for one async execution, such as request metadata or Flow orchestration.

    Tree Context#

    createContext(default) creates a context; useContext(context) reads the value of the nearest Provider above, or the default outside any Provider.

    import { createContext, useContext, renderToString } from "@vincle/core";
    
    const Theme = createContext<"light" | "dark">("light");
    
    function ThemedBox({ children }: { children: string }) {
      const theme = useContext(Theme);
      return <div class={theme === "dark" ? "dark" : "light"}>{children}</div>;
    }
    
    const html = await renderToString(
      <Theme.Provider value="dark">
        <ThemedBox>Hello</ThemedBox>
      </Theme.Provider>,
    );
    

    A Provider needs no Scope.with. Its value holds across await and across deferred Flow fragments, and concurrent renders never share it. The shape matches React, Preact and Hono, but their context objects are not interchangeable with vincle's.

    Default values and sibling isolation#

    A Provider applies to descendants through intermediate components that do not receive or forward its value as a prop. Article is an ordinary component defined for this example, not a Vincle API:

    import type { JSX } from "@vincle/core";
    import { createContext, useContext, renderToString } from "@vincle/core";
    
    const Language = createContext("fr");
    
    function Label() {
      return <span>{useContext(Language)}</span>;
    }
    
    function Article({ children }: { children: JSX.Element }) {
      return <main>{children}</main>;
    }
    
    const page = (
      <div>
        <Label />
        <Language.Provider value="en">
          <Article>
            <Label />
          </Article>
        </Language.Provider>
        <Label />
      </div>
    );
    
    const html = await renderToString(page);
    

    Output (formatted for readability):

    <div>
      <span>fr</span>
      <main><span>en</span></main>
      <span>fr</span>
    </div>
    

    Article does not know about Language. Its descendant reads en during rendering, under the Provider. Both siblings outside it read the default fr: the Provider does not change the context globally. Constructing the JSX does not call Label or Article; their functions run during rendering.

    Scope#

    Scope.key<T>(name) creates a named, typed token. Scope.with(fn) runs fn in an isolated async scope, where Scope.set(key, value) writes and Scope.get(key) reads the last value written: a value set before the writer's first await is visible to later siblings, while one set after an await races with them. get throws outside a scope or when the key has not been set.

    import { Scope, renderToString } from "@vincle/core";
    
    declare function getSession(req: Request): Promise<{ userId: string }>;
    const RequestState = Scope.key<{ userId: string; locale: string }>("app:request");
    const App = () => <main>{Scope.get(RequestState).userId}</main>;
    
    async function handleRequest(req: Request): Promise<Response> {
      const session = await getSession(req);
      const html = await Scope.with(() => {
        Scope.set(RequestState, {
          userId: session.userId,
          locale: req.headers.get("Accept-Language") ?? "en",
        });
        return renderToString(<App />);
      });
      return new Response(html, { headers: { "Content-Type": "text/html" } });
    }
    

    Scope.snapshot() copies the current map; pass the copy as the second argument of Scope.with to seed a child scope:

    const ScopedTheme = Scope.key<"light" | "dark">("app:theme");
    const ChildPage = () => <main>{Scope.get(ScopedTheme)}</main>;
    
    const childHtml = await Scope.with(async () => {
      Scope.set(ScopedTheme, "dark");
      return Scope.with(() => renderToString(<ChildPage />), Scope.snapshot());
    });
    

    Runtime support#

    Both stores use globalThis.AsyncLocalStorage or node:async_hooks. Without either, they warn and support one render at a time (async included): a second render entering a Provider or Scope.with while the first is in flight is refused. A concurrent render that reads a context without entering one may see the in-flight render's values. Enable AsyncLocalStorage for concurrent rendering.